Попробуйте этот код:
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
Выход без ToggleButton стиля
без использования XAML невозможно создать эту кнопку? –
Нет, проверьте мой обновленный ответ. – VVN