I want to style some of my listboxes' items to be radiobuttons. Here is the code I have but this style gets applied to every listboxitem.
<Window.Resources>
<Style TargetType="{x:Type ListBoxItem}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type ListBoxItem}">
<RadioButton Content="{TemplateBinding Content}"
IsChecked="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=IsSelected}"/>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</Window.Resources>
How can I do something so I can designate a listbox to have radio buttons. I imagine the designation would go something like this:
<ListBox Name="ListBox1" Width="120" Visibility="Visible" Background="{x:Null}" BorderThickness="0" Style="{StaticResource radioListBox}">
I know part of the problem is that this only styles listboxitems but I am not sure how to style the listbox itself. I would of course prefer to add in the background and border properties.
Any help would be appreciated.
You need to give your Style
a key:
<Window.Resources>
<Style x:Key="radioListBoxItem" TargetType="{x:Type ListBoxItem}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type ListBoxItem}">
<RadioButton Content="{TemplateBinding Content}"
IsChecked="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=IsSelected}"/>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</Window.Resources>
And then you would apply it to a ListBox
like:
<ListBox ItemContainerStyle="{StaticResource radioListBoxItem}" />
If you want to create a style for a ListBox
that contains the radio list box items, and some other properties, you could do that too:
<Style x:Key="radioListBox" TargetType="{x:Type ListBox}">
<Setter Property="ItemContainerStyle" Setter="{StaticResource radioListBoxItem}" />
<Setter Property="Background" Value="Navy" />
</Style>
And you'd apply it:
<ListBox Style="{StaticResource radioListBox}" />
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With