MVVMLight 要用 ​​CanExcute​​​ 判断命令可用状态需要引入命名空间 ​​using GalaSoft.MvvmLight.CommandWpf;​​​,这个命名空间在程序集 ​​GalaSoft.MvvmLight.Platform.dll​​​ 里面。 若简单的命令用 ​​using GalaSoft.MvvmLight.Command;​​​ 即可,它只需要引入 ​​GalaSoft.MvvmLight.dll​​ 程序集。

WPF 命令绑定以及命令可用状态_命名空间

WPF 命令绑定以及命令可用状态_C#_02

这里当 TextBox 控件有内容时按钮状态可用,没内容时按钮状态不可用。

XAML:

<Window.DataContext>
<local:MainVM/>
</Window.DataContext>
<Grid>
<StackPanel VerticalAlignment="Center" HorizontalAlignment="Center" Orientation="Horizontal">
<TextBlock Text="请输入文字:"/>
<TextBox Width="150" BorderBrush="Black" Text="{Binding YouContent, UpdateSourceTrigger=PropertyChanged}"/>
<Button Content="提交" Margin="10 0 0 0" Width="50" Command="{Binding SumbmitCommand}"/>
</StackPanel>
</Grid>

控件默认的绑定是在失去焦点的时候执行,这里只有一个输入控件,要实时观察命令可执行状态,需要将属性设置成 ​​UpdateSourceTrigger=PropertyChanged​​。

ViewModel:

public class MainVM : ViewModelBase
{
private string _youContent = string.Empty;
public string YouContent
{
get
{
return _youContent;
}
set
{
_youContent = value;
RaisePropertyChanged(nameof(YouContent));
}
}

private RelayCommand _submitCommand = null;
public RelayCommand SumbmitCommand
{
get
{
if (_submitCommand == null)
_submitCommand = new RelayCommand(ShowYourInput, CanExcute);
return _submitCommand;
}
set
{
_submitCommand = value;
}
}

private void ShowYourInput()
{
MessageBox.Show("你的输入:" + YouContent, "信息");
}

private bool CanExcute()
{
return !string.IsNullOrWhiteSpace(YouContent);
}
}

这里实例化 RelayCommand 的时候用的是重载构造函数 ​​RelayCommand(ShowYourInput, CanExcute)​​。