实际上是否有办法将单选按钮的Checked事件绑定到ViewModel中的命令?

时间:2016-11-25 09:16:31

标签: c# xaml mvvm command windows-10

我试过

<RadioButton Content="Boom" Command={Binding MyCommand} IsEnabled="{Binding IsChecked, Converter={StaticResource InverseBooleanConverter}, RelativeSource={RelativeSource Mode=Self}}"/>

但没有任何反应。为什么这样以及如何解决它?

2 个答案:

答案 0 :(得分:0)

以下代码按预期工作:

<RadioButton Content="Boom" Command="{Binding MyCommand}" />

也就是说,就像常规Button一样,每次点击MyCommand时都会触发RadioButton。如果你正在使用RadioButtons,这可能不是你想要的。

更有用的是将某种数据作为CommandParameter传递,以了解检查了哪个选项:

<RadioButton Content="AAA" Command="{Binding MyCommand}" CommandParameter="AAA" GroupName="MyGroup"/>
<RadioButton Content="BBB" Command="{Binding MyCommand}" CommandParameter="BBB"  GroupName="MyGroup"/>

示例命令方法:

    private ICommand _MyCommand;
    public ICommand MyCommand
    {
        get { return _MyCommand ?? (_MyCommand = new DelegateCommand(a => MyCommandMethod(a))); }
    }

    private void MyCommandMethod(object item)
    {
        Console.WriteLine("Chosen element: " + (string)item);
    }

答案 1 :(得分:0)

第1步:添加System.Windows.Interactivity参考

第2步:在XAML xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"

中添加命名空间

第3步:

<RadioButton Content="Boom" IsEnabled="{Binding IsChecked, Converter={StaticResource InverseBooleanConverter}, RelativeSource={RelativeSource Mode=Self}}">
 <i:Interaction.Triggers>
        <i:EventTrigger EventName="Checked">
            <i:InvokeCommandAction Command="{Binding MyCommand}" />
        </i:EventTrigger>
    </i:Interaction.Triggers>
</RadioButton>
相关问题