2 回答

TA貢獻1828條經(jīng)驗 獲得超4個贊
如果您使用數(shù)據(jù)綁定,請不要處理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條經(jīng)驗 獲得超6個贊
您不能在 MVVM 中綁定方法。您需要改用命令。命令由控件的默認動作行為觸發(fā)(例如,對于 Button,默認觸發(fā)是 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);
}
然后在按鈕上設(shè)置 Command 屬性:Command="{Binding ShowEntitiesCommmand}" CommandParameter="{Binding SomeParameterYoudLikeToPass}"
在這里您可以查看實現(xiàn) ICommand 的 RelayCommand 類的示例: https ://github.com/Nidrax/Veritaware.Toolkits.LightVM/blob/master/Veritaware.Toolkits.LightVM.Net/RelayCommand.cs
- 2 回答
- 0 關(guān)注
- 437 瀏覽
添加回答
舉報