How to display a different value in a WPF combobox based on selection

I couldn’t figure out a great way to title this post. Anyway, the issue I had was having a (none) value in the combobox but when it is selected show a blank combo. Those were the requirements and I wanted to do an easy solution without having to write a converter. Here is the solution using a simple style. Note, the StringResources line is where the source of the (none)string lives, You could just hard code this to your string if you aren’t pulling from a resource file.

Snippet

    <!-- Style for a combobox so that if the none value is picked, it will show up as a blank string.-->
    <Style TargetType="ComboBox" BasedOn="{StaticResource {x:Type ComboBox}}">
        <Setter Property="Foreground" Value="DarkBlue"/>
        <Setter Property="Margin" Value="0,2,0,2"/>
        <Setter Property="ItemTemplate">
            <Setter.Value>
                <DataTemplate>
                    <TextBlock Margin="0">
                        <TextBlock.Style>
                            <Style TargetType="TextBlock">
                                <Style.Setters>
                                    <Setter Property="Text" Value="{Binding}"/>
                                </Style.Setters>
                                <Style.Triggers>
                                    <MultiDataTrigger><!-- handle the display struct-->
                                        <MultiDataTrigger.Conditions>
                                            <Condition Binding="{Binding RelativeSource={RelativeSource AncestorType=ComboBoxItem},FallbackValue={x:Null}}" Value="{x:Null}"/>
                                            <Condition Binding="{Binding Text}" Value="{x:Static StringResources:WorkProgram.NoneValue}"/>
                                        </MultiDataTrigger.Conditions>
                                        <MultiDataTrigger.Setters>
                                            <Setter Property="Text" Value=" "/>
                                        </MultiDataTrigger.Setters>                                        
                                    </MultiDataTrigger>                                  
                                </Style.Triggers>
                            </Style>
                        </TextBlock.Style>
                    </TextBlock>
                </DataTemplate>
            </Setter.Value>
        </Setter>
    </Style>

Hapy coding!

Leave a Reply

Your email address will not be published. Required fields are marked *