Search code examples
c#wpfxamlbindingdatatrigger

DataTrigger with Property = ItemControl.ItemTemplate


I Am having some trouble getting this binding to work. I have several objects within SettingCollection that all have an enum property. I want to generate a control based on what the value of this is. But when I check this value with a data trigger it does not work.

Can anyone provide some insight into how i can accomplish this?

    <Window.Resources>
        <DataTemplate x:Key="CheckboxNode">
            <CheckBox IsChecked="{Binding Status}" Margin="0,5,0,0">
                <ContentPresenter Content="{Binding DisplayName}"/>
            </CheckBox>
        </DataTemplate>
        <DataTemplate x:Key="TextboxNode">
            <TextBox Text="Badgers"></TextBox>
        </DataTemplate>
</Window.Resources>
 <ItemsControl ItemsSource="{Binding SettingCollection}">
                    <ItemsControl.Style>
                        <Style TargetType="ItemsControl">
                            <Style.Triggers>
                                <DataTrigger Binding="{Binding Type}" Value="checkbox">
                                    <Setter Property="ItemsControl.ItemTemplate" Value="{StaticResource CheckboxNode}" />
                                </DataTrigger>
                                <DataTrigger Binding="{Binding Type}" Value="textbox">
                                    <Setter Property="ItemsControl.ItemTemplate" Value="{StaticResource TextboxNode}" />
                                </DataTrigger>
                            </Style.Triggers>
                        </Style>
                    </ItemsControl.Style>
                </ItemsControl>

Solution

  • If Type property is in SettingNode class, and SettingCollection is a collection of SettingNode objects, then your binding in the Datatriggers is incorrect. DataTriggers will look for Type property in ItemsControl DataContext (class with SettingCollection). Try to use DataTemplateSelector https://msdn.microsoft.com/en-us/library/system.windows.controls.datatemplateselector(v=vs.110).aspx