问题描述
我想从具有 viewmodel 的 ViewCell 绑定我的 MenuItem。
这是我的 View 单元格,有人知道进行这种绑定的正确方法吗?
我有一个 ObservableCollection<object>
填充我的 ListView
,这是我需要绑定的单元格。
<?xml version="1.0" encoding="UTF-8" ?>
<ViewCell
x:Class="DataTemp.Controls.DeviceViewCell"
xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Name="this">
<ViewCell.ContextActions>
// I've been trying these two ways
<MenuItem Command="{Binding Source={x:Reference this},Path=BindingContext.DeviceCommand}" Text="Call" />
<MenuItem Command="{Binding DeviceCommand}" Text="Call" />
</ViewCell.ContextActions>
<ViewCell.View>
<StackLayout Padding="10">
<Label Text="{Binding Name}" />
<Label Text="{Binding Number}" />
</StackLayout>
</ViewCell.View>
</ViewCell>
这是我的视图模型 我正在尝试使用断点捕获事件,但我从未进入 OnDeviceCommnad 方法。
public class DeviceViewCellviewmodel : Baseviewmodel,IDevice
{
public string Number
{
get
{
return _numberDevice;
}
set
{
_numberDevice = value;
OnPropertyChanged("Number");
}
}
public string Name
{
get
{
return _nameDevice;
}
set
{
_nameDevice = value;
OnPropertyChanged("Number");
}
}
public ICommand DeviceCommand { get; set; }
private string _nameDevice;
private string _numberDevice;
public DeviceViewCellviewmodel()
{
DeviceCommand = new Command(OnDeviceCommnad);
}
private void OnDeviceCommnad()
{
}
}
解决方法
如果你不需要传递参数,第二种方法应该可行。
<MenuItem Command="{Binding DeviceCommand}" Text="Call" />
在模型中示例代码可以如下:
public Command DeviceCommand { get; private set; }
public DeviceViewCellViewModel()
{
DeviceCommand = new Command(() =>
{
// Execute logic here
});
}
==============================更新================ ==================
从共享示例中,我发现绑定的 MainViewModel
未使用 DeviceViewCellViewModel
,因此不会调用该命令。
修改MainViewModel中的以下代码:
PaymentsAndDevices.Add(new Devices()
{
Number = rdn.Next().ToString(),Name = "I'm a device"
});
如下:
PaymentsAndDevices.Add(new DeviceViewCellViewModel()
{
Number = rdn.Next().ToString(),Name = "I'm a device"
});
然后将调用 OnDeviceCommnad
方法。