C# WPF中如何通过代码将一组RadioButton设为ToggleButton特性?
在WPF中,通过XAML可以轻松给StackPanel内的所有RadioButton批量应用ToggleButton的样式:
<StackPanel x:Name="ToolPanel" Orientation="Horizontal" Grid.Row="0"> <StackPanel.Resources> <Style TargetType="RadioButton" BasedOn="{StaticResource {x:Type ToggleButton}}"/> </StackPanel.Resources> <RadioButton x:Name="button_DrawNode" Click="Button_DrawNode_Checked" Content="Draw"/> <RadioButton x:Name="button_Connect" Click="Button_Connect_Checked" Content="Connect"/> <RadioButton x:Name="button_Move" Click="Button_Move_Checked" Content="Move"/> <RadioButton x:Name="button_Remove" Click="Button_Remove_Checked" Content="Remove"/> </StackPanel>
但用后台C#代码创建控件时,直接给StackPanel的Style属性赋值会抛出异常:
System.InvalidOperationException: ''RadioButton' TargetType does not match type of element 'StackPanel'.'
这是因为StackPanel的Style属性仅用于设置自身样式,我们需要的是给它的子元素RadioButton设置隐式样式,正确做法是将Style添加到StackPanel的Resources字典中。
后台代码实现方案
创建Style实例,指定TargetType为RadioButton并基于ToggleButton的默认样式,再将该Style添加到StackPanel的Resources中(键为typeof(RadioButton),对应XAML的隐式样式逻辑):
StackPanel stackPanel = new StackPanel { Orientation = Orientation.Horizontal }; Grid.SetRow(stackPanel, 0); // 创建RadioButton的隐式样式,基于ToggleButton默认样式 Style radioButtonToggleStyle = new Style(typeof(RadioButton)) { BasedOn = (Style)Application.Current.FindResource(typeof(ToggleButton)) }; // 将样式添加到StackPanel的Resources中 stackPanel.Resources.Add(typeof(RadioButton), radioButtonToggleStyle); // 创建RadioButton并添加到StackPanel RadioButton button_DrawNode = new RadioButton { Content = "Draw" }; RadioButton button_Connect = new RadioButton { Content = "Connect" }; RadioButton button_Move = new RadioButton { Content = "Move" }; RadioButton button_Remove = new RadioButton { Content = "Remove" }; stackPanel.Children.Add(button_DrawNode); stackPanel.Children.Add(button_Connect); stackPanel.Children.Add(button_Move); stackPanel.Children.Add(button_Remove);
说明
- 隐式样式会自动应用到作用域内所有匹配
TargetType的控件,这里StackPanel的Resources就是作用域,内部所有RadioButton无需逐个设置就能自动使用该样式。 Application.Current.FindResource(typeof(ToggleButton))用于获取WPF内置的ToggleButton默认样式,和XAML中{StaticResource {x:Type ToggleButton}}的逻辑完全一致。
内容的提问来源于stack exchange,提问作者Experiment-626
相关产品推荐
相关产品推荐

