我正在尝试实现WPF MVVM应用程序。我是这个平台的初学者。我只需要为我的SaveCommand实现一个CanExecute方法
这是代码
WPF XML代码
<Canvas Height="283" Name="canvas1" Width="321">
<Label Canvas.Left="6" Canvas.Top="6" Content="First Name" Height="25" Width="91" />
<Label Canvas.Left="6" Canvas.Top="37" Content="Last Name" Height="25" Width="91" />
<TextBox Canvas.Left="103" Canvas.Top="10" Height="21" Width="199" Text="{Binding Path=FirstName, UpdateSourceTrigger=PropertyChanged}"/>
<TextBox Canvas.Left="103" Canvas.Top="37" Height="21" Width="199" Text="{Binding Path=LastName, UpdateSourceTrigger=PropertyChanged}"/>
<Button Canvas.Left="228" Canvas.Top="241" Content="Save" Height="23" Width="74" Command="{Binding SaveCommand}" />
<TextBlock Canvas.Left="28" Canvas.Top="110" Height="19" Width="259" Text="{Binding Path=FullName}"/>
</Canvas>
C#ViewModel代码
public CustomerViewModel(IEventAggregator eventAggregator, IUnityContainer container, ILoggerFacade logger)
: base(eventAggregator, container, logger)
{
logger.Log("View Model Initialized", Category.Debug, Priority.None);
InitializeCommands();
}
public DelegateCommand<object> SaveCommand { get; set; }
private string firstName;
public string FirstName
{
get { return firstName; }
set {
firstName = value;
RaisePropertyChanged("FirstName");
}
}
private string lastName;
public string LastName
{
get { return lastName; }
set {
lastName = value;
RaisePropertyChanged("LastName");
}
}
private string fullName;
public string FullName
{
get { return fullName; }
set {
fullName = value;
RaisePropertyChanged("FullName");
}
}
private void InitializeCommands()
{
SaveCommand = new DelegateCommand<object>(OnSaveCommand, CanSaveExcute);
}
private bool CanSaveExcute(object obj)
{
if (string.IsNullOrEmpty(firstName) || string.IsNullOrEmpty(lastName))
return false;
return true;
}
private void OnSaveCommand(object obj)
{
FullName = FirstName + " " + LastName;
}
没有Can CanSaveExcute它可以正常工作。设置CanSaveExcute后,该按钮保持禁用状态,并且不会启用文本更改。据我所知,这是要走的路。
请告诉我我做错了什么。
谢谢
答案 0 :(得分:3)
您还应该引发“CanExecuteChanged”事件,否则接收方必须永久重新访问您的命令,以确定它是否可以执行。您可以使用“RaiseCanExecuteChanged”方法,描述为here
修改强>
如果您不介意开销,可以在致电物业设定者this.SaveCommand.RaiseCanExecuteChanged()
后致电RaisePropertyChanged("FullName");
。如果您RaisePropertyChanged
方法是虚拟的,则可以放置RaiseCanExecuteChanged()
。