Search code examples
c#wpfxamlcombobox

How to display "No Items" content in ComboBox if target ItemsSource is null?


I am trying to create a Combobox with updatable collection. Than I would to display special content inside combobox if collection which binding to combobox in null.

I had try to set TargetNullValue parameter but it's display content not as I expected.

<ComboBox ItemsSource="{Binding MyCollection, UpdateSourceTrigger=PropertyChanged, TargetNullValue='No Items'}"/>

What I Have Now

What I have now

What I Expect

What I expect


Solution

  • You may replace the ComboBox's Template when it has no items, e.g. with a TextBlock or any other visual element.

    <ComboBox>
        <ComboBox.Style>
            <Style TargetType="ComboBox">
                <Style.Triggers>
                    <Trigger Property="HasItems" Value="False">
                        <Setter Property="Template">
                            <Setter.Value>
                                <ControlTemplate TargetType="ComboBox">
                                    <TextBlock Text="No Items"/>
                                </ControlTemplate>
                            </Setter.Value>
                        </Setter>
                    </Trigger>
                </Style.Triggers>
            </Style>
        </ComboBox.Style>
    </ComboBox>