问题:如何在没有xaml的代码中以编程方式创建相同的按钮
XAML:
<RadioButton Style="{StaticResource {x:Type ToggleButton}}"/>
我试着制作这样的按钮 C#:
RadioButton radioButt = new RadioButton();
radioButt.Style = new Style(typeof(ToggleButton);
但是当我在视觉后面的代码中创建按钮时,他们没有改变
答案 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);
}
}
}
}