You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C# WPF中如何通过代码将一组RadioButton设为ToggleButton特性?

实现StackPanel内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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.19 08:38:14