WPF 命令绑定以及命令可用状态

2021/8/16 23:36:23

本文主要是介绍WPF 命令绑定以及命令可用状态,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

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

这里当 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)




参考:

https://www.cnblogs.com/wzh2010/p/6557037.html



这篇关于WPF 命令绑定以及命令可用状态的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程