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

1

5

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.

Womanizer answered 28/6, 2013 at 15:51 Comment(0)
V
10

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}" />
Vietcong answered 28/6, 2013 at 15:56 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.