Silverlight中CheckBox的MVVM-Light EventToCommand行为已选中/未选中 [英] MVVM-Light EventToCommand Behavior for CheckBox Checked/Unchecked in Silverlight

查看:101
本文介绍了Silverlight中CheckBox的MVVM-Light EventToCommand行为已选中/未选中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想处理Checkbox控件的Checked和Unchecked事件,并在ViewModel中执行命令.我为Checked和Unchecked事件连接了EventTrigger,如下所示:

I would like to handle the Checked and Unchecked events of a Checkbox control and execute a command in my ViewModel. I wired up an EventTrigger for both the Checked and Unchecked events as follows:

<CheckBox x:Name="chkIsExtendedHr" IsChecked="{Binding Schedule.Is24Hour, Mode=TwoWay}">
    <i:Interaction.Triggers>
        <i:EventTrigger EventName="Checked">
            <GalaSoft_MvvmLight_Command:EventToCommand 
                CommandParameter="{Binding IsChecked, ElementName=chkIsExtendedHr}"
                Command="{Binding Path=SetCloseTime, Mode=OneWay}" />
        </i:EventTrigger>
        <i:EventTrigger EventName="Unchecked">
            <GalaSoft_MvvmLight_Command:EventToCommand 
                CommandParameter="{Binding IsChecked, ElementName=chkIsExtendedHr}"
                Command="{Binding Path=SetCloseTime, Mode=OneWay}" />
        </i:EventTrigger>
    </i:Interaction.Triggers>
</CheckBox>

我在ViewModel中定义了一个RelayCommand并为其连线了一个动作:

I defined a RelayCommand in my ViewModel and wired up an action for it:

public RelayCommand<Boolean> SetCloseTime{ get; private set; }

   ...

SetCloseTime= new RelayCommand<bool>(ExecuteSetCloseTime);

命令操作中的参数始终解析为CheckBox的先前状态,例如选中CheckBox时返回false,而取消选中CheckBox时返回true.

The parameter in the action for the command always resolves to the previous state of the CheckBox, e.g. false when the CheckBox is checked, and true when the CheckBox is unchecked.

void ExecuteSetCloseTime(bool isChecked) 
{
    if (isChecked)
    {
        // do something
    }
}

这是预期的行为吗?

我有一个解决方法,在该方法中,我有分别用于已检查"和未检查"的触发器(和命令),并使用RelayCommand而不是RelayCommand<bool>.选中和取消选中CheckBox时,每个命令都可以正确执行.但是感觉有点脏-比在我的ViewModel中包含UI代码还要肮脏:)

I have a workaround where I have separate triggers (and commands) for the Checked and Unchecked and use a RelayCommand instead of RelayCommand<bool>. Each command executes correctly when the CheckBox is checked and unchecked. Feels a little dirty though - even dirtier than having UI code in my ViewModel :)

谢谢

推荐答案

您为什么不在Schedule.Is24Hour中处理您的操作.在setter中,您始终可以看到该属性的更改时间.

Why don't you handle your actions in your Schedule.Is24Hour. In setter you always can see when that property is changed.

这篇关于Silverlight中CheckBox的MVVM-Light EventToCommand行为已选中/未选中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆