Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I style certain WPF listboxes to be radio buttons?

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.

like image 657
donL Avatar asked Jan 13 '23 01:01

donL


1 Answers

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}" />
like image 73
Abe Heidebrecht Avatar answered Feb 07 '23 11:02

Abe Heidebrecht