gpt4 book ai didi

wpf - 使用 DelegateCommand 的 CanExecute 操作

转载 作者:行者123 更新时间:2023-12-04 19:34:24 26 4
gpt4 key购买 nike

我在 Prism/WPF 项目中有一个像这样的 ViewModel 类。

public class ContentViewModel : ViewModelBase, IContentViewModel
{
public ContentViewModel(IPersonService personService)
{
Person = personService.GetPerson();
SaveCommand = new DelegateCommand(Save, CanSave);
}

public Person Person { get; set; }

public DelegateCommand SaveCommand { get; set; }

private void Save()
{
// Save actions here...
}

private bool CanSave()
{
return Person.Error == null;
}
}

上面ViewModel中使用的person类型定义如下:

public class Person : INotifyPropertyChanged, IDataErrorInfo
{
private string _firstName;
public string FirstName
{
get { return _firstName; }
set
{
_firstName = value;
OnPropertyChanged("FirstName");
}
}

// other properties are implemented in the same way as above...

public event PropertyChangedEventHandler PropertyChanged;

protected void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}

private string _error;
public string Error
{
get
{
return _error;
}
}

public string this[string columnName]
{
get
{
_error = null;
switch (columnName)
{
// logic here to validate columns...
}
return _error;
}
}
}

ContentViewModel 的实例被设置为 View 的 DataContext。在 View 中,我按如下方式使用了对 Person 的绑定(bind):

<TextBox Text="{Binding Person.FirstName, ValidatesOnDataErrors=True}" />
<Button Content="Save" Command="{Binding SaveCommand}" />

当我对绑定(bind)到 Person 属性(如 FirstName)的 TextBox 进行更改并单击“保存”时,我可以在 ViewModel 命令处理程序中看到更改。但是,如果这些属性中的任何一个在验证中失败,则永远不会执行 CanSave,并且永远不会禁用按钮。

在上述情况下,如何禁用基于 DelegateCommand 的 CanExecute 操作处理程序的按钮?

最佳答案

在 ContentViewModel 的构造函数中添加这一行

public ContentViewModel(IPersonService personService)
{
//GetPerson
Person.PropertyChanged +=person_PropertyChanged;
}

然后编写一个方法来处理您调用 CommandManager.InvalidateRequerySuggested() 或 SaveCommand.RaiseCanExecuteChanged() 的事件

private void person_PropertyChanged(object sender, EventArgs args)
{
CommandManager.InvalidateRequerySuggested();
//SaveCommand.RaiseCanExecuteChanged()
}

希望这能奏效。 :-)

关于wpf - 使用 DelegateCommand 的 CanExecute 操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9653874/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com