Search code examples
wpfxamldata-binding

WPF Select ComboBox text style based on variable


I have a ComboBox and I'd like to be able to change the style of the text inside the ComboBoxItem based on an attribute of the ComboBoxItem.

<ComboBox ItemsSource="{Binding Countries}">
    <ComboBox.ItemTemplate>
        <DataTemplate>
            <ContentControl Content="{Binding}" Focusable="False">
                <ContentControl.Style>
                    <Style TargetType="{x:Type ContentControl}">
                        <Setter Property="ContentTemplate">
                            <Setter.Value>
                                <DataTemplate>
                                    <TextBlock Text="{Binding Name}" Style="{StaticResource MyStyle}" />
                                </DataTemplate>
                            </Setter.Value>
                        </Setter>
                    </Style>
                </ContentControl.Style>
            </ContentControl>
        </DataTemplate>
    </ComboBox.ItemTemplate>

I've been trying to set the TextBlock Style from MyStyle to a different one if the Country's attribute IsWestern is true, but I am not managing. I figure I need a Trigger somewhere, but I can't figure it out and added a variety, but none worked so far.


Solution

  • use DataTrigger to change ContentTemplate:

    <Style TargetType="{x:Type ContentControl}">
        <Setter Property="ContentTemplate">
            <Setter.Value>
                <DataTemplate>
                    <TextBlock Text="{Binding Name}" Style="{StaticResource MyStyle}" />
                </DataTemplate>
            </Setter.Value>
        </Setter>
        <Style.Triggers>
            <DataTrigger Binding="{Binding Path=IsWestern}" Value="True">
                <Setter Property="ContentTemplate">
                    <Setter.Value>
                        <DataTemplate>
                            <TextBlock Text="{Binding Name}" Style="{StaticResource WesternStyle}" />
                        </DataTemplate>
                    </Setter.Value>
                </Setter>
            </DataTrigger>
        </Style.Triggers>
    </Style>
    

    alternatively include <DataTrigger Binding="{Binding Path=IsWestern}" Value="True"> in TextBlock Style (MyStyle) and change required TextBlock properties there:

    <Style x:Key="MyStyle" TargetType="TextBlock">
        <Setter Property="LineStackingStrategy" Value="BlockLineHeight"></Setter>
    
        <Style.Triggers>
            <DataTrigger Binding="{Binding Path=IsWestern}" Value="True">
                <Setter Property="Padding" Value="20,0,0,0"></Setter>
            </DataTrigger>
        </Style.Triggers>
    
    </Style>