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 命令绑定以及命令可用状态的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-07-02springboot项目无法注册到nacos-icode9专业技术文章分享
- 2024-06-26结对编程到底难不难?答案在这里
- 2024-06-19《2023版Java工程师》课程升级公告
- 2024-06-15matplotlib作图不显示3D图,怎么办?
- 2024-06-1503-Loki 日志监控
- 2024-06-1504-让LLM理解知识 -Prompt
- 2024-06-05做软件测试需要懂代码吗?
- 2024-06-0514-ShardingSphere的分布式主键实现
- 2024-06-03为什么以及如何要进行架构设计权衡?
- 2024-05-31全网首发第二弹!软考2024年5月《软件设计师》真题+解析+答案!(11-20题)