我的 ViewModel 中有这样的东西:
public enum WorkState
{
Idle, Working, Stopping
};
public class MainViewModel : ViewModelBase
{
public const string StatePropertyName = "State";
private WorkState _state = WorkState.Idle;
public WorkState State
{
get
{ return _state; }
set
{
if (_state == value)
{
return;
}
RaisePropertyChanging(StatePropertyName);
_state = value;
RaisePropertyChanged(StatePropertyName);
StartStopCommand.RaiseCanExecuteChanged(); // <—————————————
}
}
private RelayCommand _startStopCommand;
public RelayCommand StartStopCommand
{
get
{
return _startStopCommand
?? (_startStopCommand = new RelayCommand(
() =>
{
if (State == WorkState.Idle)
{
State = WorkState.Working;
}
else if (State == WorkState.Working)
{
State = WorkState.Stopping;
new Thread(() =>
{
Thread.Sleep(5000);
State = WorkState.Idle;
}).Start();
}
},
() => (State == WorkState.Idle ||
(State == WorkState.Working)));
}
}
}
我的视图中的按钮:
<Button Command="{Binding StartStopCommand}">
<Button.Style>
<Style>
<Style.Triggers>
<DataTrigger Binding="{Binding State}" Value="{x:Static vm:WorkState.Idle}">
<Setter Property="Button.Content" Value="Start"/>
</DataTrigger>
<DataTrigger Binding="{Binding State}" Value="{x:Static vm:WorkState.Working}">
<Setter Property="Button.Content" Value="Stop"/>
</DataTrigger>
<DataTrigger Binding="{Binding State}" Value="{x:Static vm:WorkState.Stopping}">
<Setter Property="Button.Content" Value="Stop"/>
</DataTrigger>
</Style.Triggers>
</Style>
</Button.Style>
</Button>
但是当我按下停止按钮并且状态属性更改为空闲时,按钮只会将其文本更改为“开始”,但在我单击窗口中的某个位置之前保持禁用状态。
我将 RaiseCanExecuteChanged 添加到 State 属性的设置器中,但它没有帮助。
我究竟做错了什么?
此外,我不确定这种在同一命令中使用 Start/Stop 和 DataTriggers 设置按钮文本的方法是最好的,所以如果有人分享更好的方法,我将不胜感激。