Justin Pihony
Justin Pihony

Reputation: 67075

ListBox ItemTemplate based on parent binding value

Basically, I am looking to create a custom template for my listitems. One template will use checkboxes, while the other will use radioboxes. This is meant to emulate when multiselect is allowed or not. However, I have tried many different ways, with the most promising being the DataTemplateSelector, however I need to create a Dependency Property so that I can pass in the boolean IsMultiSelect value. But, I need a DependencyObject within the Selector, and the closest I can get is the contentpresenter. I know I can get the parent control based off of that, but that seems like a hack. Is there any way to accomplish what I am looking to do?

Upvotes: 1

Views: 627

Answers (1)

max
max

Reputation: 34417

I'm not completely sure if I understood everything correctly, but this may be helpful:

<ListBox SelectionMode="Multiple">
<!--<ListBox SelectionMode="Single">-->
    <ListBox.Items>
        <TextBlock Text="Test 1" />
        <TextBlock Text="Test 2" />
        <TextBlock Text="Test 3" />
        <TextBlock Text="Test 4" />
        <TextBlock Text="Test 5" />
        <TextBlock Text="Test 6" />
    </ListBox.Items>
    <ListBox.Style>
        <Style TargetType="{x:Type ListBox}">
            <Style.Resources>
                <DataTemplate x:Key="SingleSelectionModeItemTemplate">
                    <RadioButton IsChecked="{Binding Path=IsSelected,
                                                     RelativeSource={RelativeSource AncestorType={x:Type ListBoxItem}},
                                                     Mode=TwoWay}"
                                 Content="{Binding}" />
                </DataTemplate>
                <DataTemplate x:Key="MultiSelectionModeItemTemplate">
                    <CheckBox IsChecked="{Binding Path=IsSelected,
                                                  RelativeSource={RelativeSource AncestorType={x:Type ListBoxItem}},
                                                  Mode=TwoWay}"
                              Content="{Binding}" />
                </DataTemplate>
            </Style.Resources>
            <Style.Triggers>
                <Trigger Property="SelectionMode"
                         Value="Single">
                    <Setter Property="ItemTemplate" Value="{StaticResource SingleSelectionModeItemTemplate}" />
                </Trigger>
                <Trigger Property="SelectionMode"
                         Value="Multiple">
                    <Setter Property="ItemTemplate" Value="{StaticResource MultiSelectionModeItemTemplate}" />
                </Trigger>
            </Style.Triggers>
        </Style>
    </ListBox.Style>
</ListBox>

Upvotes: 1

Related Questions