2 回答
TA贡献1828条经验 获得超4个赞
如果您使用数据绑定,请不要处理Click事件。使用Button.Command,并将其绑定到视图模型的ICommand属性:
public class SomeVm
{
public SomeVm()
{
// initialize SomeCommand here;
// usually you need RelayCommand/DelegateCommand
SomeCommand = new RelayCommand(SomeMethod);
}
public ICommand SomeCommand { get; }
private void SomeMethod()
{
}
}
XAML:
<Button Content="Click me!" Command="{Binding SomeCommand}"/>
TA贡献1772条经验 获得超6个赞
您不能在 MVVM 中绑定方法。您需要改用命令。命令由控件的默认动作行为触发(例如,对于 Button,默认触发是 Click)(如果您想将命令绑定到默认之外的其他事件,则需要编写一些交互逻辑或使用支持它的库)。
这是命令的示例:
private ICommand _ShowEntitiesCommand;
public ICommand ShowEntitiesCommmand
{
get
{
if (_ShowEntitiesCommand == null)
{
_ShowEntitiesCommand = new RelayCommand(ShowEntities);
}
return _ShowEntitiesCommand;
}
}
private void ShowEntities(object parameter)
{
SelectedViewModel = viewModelLocator.Get(parameter);
}
然后在按钮上设置 Command 属性:Command="{Binding ShowEntitiesCommmand}" CommandParameter="{Binding SomeParameterYoudLikeToPass}"
在这里您可以查看实现 ICommand 的 RelayCommand 类的示例: https ://github.com/Nidrax/Veritaware.Toolkits.LightVM/blob/master/Veritaware.Toolkits.LightVM.Net/RelayCommand.cs
- 2 回答
- 0 关注
- 399 浏览
添加回答
举报