好吧,在摆弄了 MVVM 灯以让我的按钮在我想要的时候启用和禁用......我把东西混在一起直到它起作用。
但是,我只知道我在这里做错了什么。我在被调用的同一区域中有 RaiseCanExecuteChanged 和 CanExecute。当然这不是它的做法吗?
这是我的xml
<Button Margin="10, 25, 10, 25" VerticalAlignment="Center" HorizontalAlignment="Center" Width="50" Height="50" Grid.Column="1" Grid.Row="3" Content="Host">
<i:Interaction.Triggers>
<i:EventTrigger EventName="Click">
<mvvmLight:EventToCommand Command="{Binding HostChat}" MustToggleIsEnabled="True" />
</i:EventTrigger>
</i:Interaction.Triggers>
</Button>
这是我的代码
public override void InitializeViewAndViewModel()
{
view = UnityContainer.Resolve<LoginPromptView>();
viewModel = UnityContainer.Resolve<LoginPromptViewModel>();
view.DataContext = viewModel;
InjectViewIntoRegion(RegionNames.PopUpRegion, view, true);
viewModel.HostChat = new DelegateCommand(ExecuteHostChat, CanHostChat);
viewModel.PropertyChanged += new System.ComponentModel.PropertyChangedEventHandler(ViewModelPropertyChanged);
}
void ViewModelPropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
{
if (e.PropertyName == "Name" || e.PropertyName == "Port" || e.PropertyName == "Address")
{
(viewModel.HostChat as DelegateCommand).RaiseCanExecuteChanged();
(viewModel.HostChat as DelegateCommand).CanExecute();
}
}
public void ExecuteHostChat()
{
}
public bool CanHostChat()
{
if (String.IsNullOrEmpty(viewModel.Address) ||
String.IsNullOrEmpty(viewModel.Port) ||
String.IsNullOrEmpty(viewModel.Name))
{
return false;
}
else
return true;
}
看看这两个是怎么在一起的?这肯定是不对的。我的意思是……它对我有用……但它似乎有些不对劲。RaiseCanExecuteChanged 不应该调用 CanExecute 吗?它没有......所以如果我没有那个 CanExecute ,我的控件永远不会像我需要的那样切换它的 IsEnabled 。
(viewModel.HostChat as DelegateCommand).RaiseCanExecuteChanged();
(viewModel.HostChat as DelegateCommand).CanExecute();
编辑:
如果我最终使用按钮的 Command 属性将我的命令绑定到...一切正常。我可以删除 CanExecute 并留下 RaiseCanExecuteChanged ,一切正常。
像这样......这工作得很好。
<Button Command="{Binding HostChat}" Margin="10, 25, 10, 25" VerticalAlignment="Center" HorizontalAlignment="Center" Width="50" Height="50" Grid.Column="1" Grid.Row="3" Content="Host">
</Button>
void ViewModelPropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
{
if (e.PropertyName == "Name" || e.PropertyName == "Port" || e.PropertyName == "Address")
{
(viewModel.HostChat as DelegateCommand).RaiseCanExecuteChanged();
//(viewModel.HostChat as DelegateCommand).CanExecute();
//CommandManager.InvalidateRequerySuggested();
}
}