WPF中如何将RadioButton的Content属性作为CommandParameter传递?
问题出在Style的Setter绑定上下文:默认情况下,{Binding Path=Content}会尝试绑定当前DataContext(通常是ViewModel)的Content属性,而非RadioButton自身的Content。要绑定到控件自身属性,需通过RelativeSource指定绑定源为RadioButton实例。
修改后的Style代码如下:
<Style TargetType="RadioButton"> <Setter Property="VerticalAlignment" Value="Center"/> <Setter Property="HorizontalAlignment" Value="Left"/> <Setter Property="Margin" Value="5"/> <Setter Property="Command" Value="{Binding SelectionChangedCommand}"/> <!-- 绑定到当前RadioButton自身的Content属性 --> <Setter Property="CommandParameter" Value="{Binding Path=Content, RelativeSource={RelativeSource Self}}"/> </Style>
修改后,所有应用该Style的RadioButton都会自动将自身Content作为CommandParameter传递给SelectionChangedCommand,你之前手动设置CommandParameter="Transom Count"的RadioButton可以移除该属性,保持代码一致性。
内容的提问来源于stack exchange,提问作者Gokhan
相关产品推荐
相关产品推荐

