以编程方式使用ToggleButton样式创建RadioButton

时间:2016-02-18 12:24:56

标签: c# wpf xaml

问题:如何在没有xaml的代码中以编程方式创建相同的按钮

XAML:

<RadioButton Style="{StaticResource {x:Type ToggleButton}}"/>

我试着制作这样的按钮 C#:

RadioButton radioButt = new RadioButton();
radioButt.Style = new Style(typeof(ToggleButton);

但是当我在视觉后面的代码中创建按钮时,他们没有改变

1 个答案:

答案 0 :(得分:0)

试试这段代码:

public MainWindow()
{
    InitializeComponent();

    for (int i = 0; i < 4; i++)
    {
        RadioButton rb = new RadioButton() { Content = "Radio button " + i, IsChecked = i == 0  };
        rb.Checked += (sender, args) => 
        {
            Console.WriteLine("Pressed " + ( sender as RadioButton ).Tag );
        };
        rb.Unchecked += (sender, args) => { /* Do stuff */ };
        rb.Tag = i;

        MyStackPanel.Children.Add( rb );
     }
}

XAML

    <Style BasedOn="{StaticResource {x:Type ToggleButton}}"
           TargetType="RadioButton"/>

工作代码:

这是我的XAML代码:

<Window x:Class="Test.Window1"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="Window1" Height="300" Width="300" WindowStartupLocation="CenterScreen">
    <Window.Resources>
        <Style BasedOn="{StaticResource {x:Type ToggleButton}}"
       TargetType="RadioButton"/>
    </Window.Resources>
    <Grid>

        <StackPanel Name="MyStackPanel">

        </StackPanel>

    </Grid>
</Window>

cs档案:

public partial class Window1 : Window
    {
        public Window1()
        {
            InitializeComponent();

            for (int i = 0; i < 4; i++)
            {
                RadioButton rb = new RadioButton() { Content = "Radio button " + i, IsChecked = i == 0 };
                rb.Checked += (sender, args) =>
                {
                    Console.WriteLine("Pressed " + (sender as RadioButton).Tag);
                };
                rb.Unchecked += (sender, args) => { /* Do stuff */ };
                rb.Tag = i;

                MyStackPanel.Children.Add(rb);
            }
        }  
  }
}

使用Togglebutton样式输出 Output with Togglebutton style

没有Togglebutton样式的输出 Output without Togglebutton style

相关问题