WPF MVVM 文本框 按回车触发Command

 

        <TextBox HorizontalAlignment="Left" Height="24" Margin="10,10,0,0" 
            Text="{Binding SearchText, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" 
            TextWrapping="Wrap" VerticalAlignment="Top" Width="161">
            <TextBox.InputBindings>
                <!--键盘事件绑定-->
                <KeyBinding Command="{Binding Search_Click}" Key="Enter"/>
                <!--鼠标事件绑定-->
                <MouseBinding Command="{Binding ButtonClick}" MouseAction="LeftDoubleClick"/>
            </TextBox.InputBindings>
        </TextBox>

 

  • 5
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
WPF中,可以使用MVVM模式来实现CheckBox的事件触发MVVM模式是一种常用的WPF应用程序架构,它将应用程序分成三个部分:模型、视图和视图模型。视图模型(ViewModel)是视图(View)和模型(Model)之间的中介,处理视图和模型之间的交互。 对于CheckBox控件,可以在ViewModel中定义一个布尔类型的属性来表示CheckBox是否选中,然后使用数据绑定将这个属性绑定到CheckBox控件的IsChecked属性。当CheckBox的状态发生改变时,会自动更新ViewModel中的属性值。如果需要在CheckBox状态改变时执行一些特定操作,可以在ViewModel中定义一个Command属性,并将其绑定到CheckBox的Command属性上。在Command的Execute方法中可以编写具体的操作逻辑,从而实现CheckBox状态改变时的事件触发。 以下是一个简单的示例: ViewModel代码: ``` public class MyViewModel : INotifyPropertyChanged { private bool _isChecked; public bool IsChecked { get { return _isChecked; } set { if (_isChecked != value) { _isChecked = value; OnPropertyChanged(nameof(IsChecked)); MyCommand.Execute(null); } } } public ICommand MyCommand { get; set; } public MyViewModel() { MyCommand = new RelayCommand(DoSomething); } private void DoSomething() { // 在这里编写CheckBox状态改变时需要执行的操作 } public event PropertyChangedEventHandler PropertyChanged; protected virtual void OnPropertyChanged(string propertyName) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } } ``` View代码: ``` <CheckBox IsChecked="{Binding IsChecked}"> <i:Interaction.Triggers> <i:EventTrigger EventName="Checked"> <i:InvokeCommandAction Command="{Binding MyCommand}" /> </i:EventTrigger> <i:EventTrigger EventName="Unchecked"> <i:InvokeCommandAction Command="{Binding MyCommand}" /> </i:EventTrigger> </i:Interaction.Triggers> </CheckBox> ``` 注意,在View中使用了System.Windows.Interactivity命名空间中的EventTrigger和InvokeCommandAction类来实现事件触发。同时,需要将ViewModel中的MyCommand属性设置为RelayCommand类型,这是一个常用的ICommand实现类,可以在NuGet包管理器中安装MVVMLight库来获取该类。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值