【问题标题】:Is there actually a way to bind Checked event of a radio button to a command in the ViewModel?实际上有没有办法将单选按钮的 Checked 事件绑定到 ViewModel 中的命令?
【发布时间】:2017-04-09 15:21:23
【问题描述】:
我试过了
<RadioButton Content="Boom" Command={Binding MyCommand} IsEnabled="{Binding IsChecked, Converter={StaticResource InverseBooleanConverter}, RelativeSource={RelativeSource Mode=Self}}"/>
但什么也没发生。为什么会这样以及如何解决?
【问题讨论】:
标签:
c#
xaml
mvvm
command
windows-10
【解决方案1】:
第 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>
【解决方案2】:
以下代码按预期工作:
<RadioButton Content="Boom" Command="{Binding MyCommand}" />
也就是说,与普通的Button 一样,每次单击RadioButton 时都会触发MyCommand。如果您使用的是 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);
}