首页 > Windows开发 > 详细

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

时间:2021-08-17 10:39:57      阅读:21      评论:0      收藏:0      [点我收藏+]

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)




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

原文:https://www.cnblogs.com/huvjie/p/15150442.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!