【问题标题】:How to Bind a Command to a CheckBox如何将命令绑定到复选框
【发布时间】:2012-03-06 18:51:00
【问题描述】:

我正在尝试将复选框 checkchange 事件绑定到命令 - MVVM 为什么这不起作用?或在按钮上执行相同操作时执行任何操作?

<CheckBox x:Name="radRefresh" IsChecked="{BindingREADY, Mode=TwoWay}" Command="{Binding Refresh_Command}" Content=" Refresh "  Margin="10,25,0,0"  />

<Button Command="{Binding Refresh_Command}" />

谢谢

【问题讨论】:

    标签: wpf checkbox mvvm


    【解决方案1】:

    这会起作用...

    <i:Interaction.Triggers> <i:EventTrigger EventName="Click"> <cmd:EventToCommand Command="{Binding Path=YourCommand,Mode=OneWay}" CommandParameter="{Binding IsChecked, ElementName=YourCheckBox}"></cmd:EventToCommand> </i:EventTrigger> </i:Interaction.Triggers>

    我在哪里

    xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
    

    为 cmd 添加命名空间

        xmlns:cmd="clr-namespace:GalaSoft.MvvmLight.Command;assembly=GalaSoft.MvvmLight.Extras.WPF4"
    

    如果您使用 MVVMLight 框架,这是 MVVM 的首选方法之一。

    【讨论】:

    • 什么是 cmd 命名空间,不是来自 MVVM Light 工具包吗?
    • 感谢您的澄清。问题是,并不是每个人都在使用 MVVM Light(我更喜欢 Prism),所以称它为“唯一首选方式”有点强 :-)
    • 可以在here找到一些不使用 MVVM Light 的示例。
    【解决方案2】:

    这是一个简单的情况:

    1. 将 CheckBox.IsChecked 绑定到 ViewModel 中的布尔值。
    2. 在您的视图模型中,订阅属性更改事件并观察布尔值是否发生变化。

    完成。

    【讨论】:

      【解决方案3】:

      您无需将其绑定到事件。 您需要做的就是将 IsChecked 绑定到一个布尔依赖属性,并在其设置器上执行您想要的任何逻辑。

      像这样 -

      <CheckBox x:Name="radRefresh" IsChecked="{Binding IsChecked, Mode=TwoWay}" Content=" Refresh "  Margin="10,25,0,0"  />
      

      此 xaml 应将您绑定到 VM 上的此属性

        public bool IsChecked
        {
            get
            {
                return isChecked;
            }
            set
            {
                isChecked = value;
                NotifyPropertChanged("IsChecked");
      
                //Add any logic you'd like here
             }
         }
      

      【讨论】:

      • 嗨 Orchestraor,我喜欢你的回答,请澄清我的一些事情。你说,我需要将我的属性绑定到一个依赖属性,所以首先我必须在我的虚拟机中创建一个依赖属性?我是否需要设置 Content="Refresh" 属性或者它可以不刷新它?
      • 嗨 Manav,是的,您必须像我在代码中指定的那样创建一个属性。我称它为依赖属性,因为它引发了 NotifyPropertChanged 事件。这就是为什么你的 ViewModel 必须实现 INotifyPropertChanged 接口。除了“IsChecked”属性之外,您不需要设置任何其他属性,我只添加它们是因为它们存在于 Jon 的问题中。
      【解决方案4】:

      那是因为只有少数控件(我的头顶的ButtonMenuItem)实现了直接绑定命令的功能。

      如果您需要绑定到控件,我建议您创建一个UserControl,以便在代码隐藏中更改 CheckBox 的属性 IsChecked 时执行 ViewModel 的命令。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-11-16
        • 1970-01-01
        • 2016-01-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多