Search code examples
c#wpfdatatrigger

How to get the value of the item source in datatrigger in a combobox?


I have a combobox which itemsource is a collection of type MyTpye. My type is something like that:

Class MyClass
{
    long ID;
    string Description;
    decimal Value;
}

For DisplayMemberPath I am using the Value property. The problema is that is a decimal, not decimal?, so in the case that ID is 0 then the value is 0 too. I would like to display in this case 0.

So I am trying to use a datatrigger in this way:

<ComboBox Name="myComboBox"
          DisplayMemberPath="Value"
          ItemsSource="{Biniding MyCollection}"
          SelectedItem="{Binding Path=MySelectedItem}">
    <ComboBox.Style>
        <Style TargetType="ComboBox">
            <Style.Triggers>
                <DataTrigger Binding="{Binding ???, path=ID}" Value="0">
                    <Setter Property="DisplayMemberPath" Value="{x:Null}"/>
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </ComboBox.Style>
</ComboBox>

The problem is that in the binding of the datatrigger, I don't know how to get the item of the collection that is the sorce of the item of the combobox, and from this item, the ID property.

Thanks.


Solution

  • Get rid of the DisplayMemberPath and use an ItemTemplate to display either the value of the Value property or something else:

    <ComboBox Name="myComboBox"
              ItemsSource="{Binding MyCollection}"
              SelectedItem="{Binding Path=MySelectedItem}">
        <ComboBox.ItemTemplate>
            <DataTemplate>
                <TextBlock>
                    <TextBlock.Style>
                        <Style TargetType="TextBlock">
                            <Setter Property="Text" Value="{Binding Value}" />
                            <Style.Triggers>
                                <DataTrigger Binding="{Binding Value}" Value="0">
                                    <Setter Property="Text" Value="..." />
                                </DataTrigger>
                            </Style.Triggers>
                        </Style>
                    </TextBlock.Style>
                </TextBlock>
            </DataTemplate>
        </ComboBox.ItemTemplate>
    </ComboBox> 
    

    In the above example, "..." will be displayed instead of "0" for any item with a Value of 0.