WPF ComboBox 与对象列表绑定,并且在所选项目中显示的值与项目列表中的值不同

WPF ComboBox bound with object list and display less different value in selected item than in the item list

我有这个组合框:

<ComboBox
    ItemsSource="{Binding imageFormats}">
    <ComboBox.ItemTemplate>
        <DataTemplate>
            <DockPanel>
                <TextBlock DockPanel.Dock="Left" Text="{Binding Extension}" />
                <TextBlock DockPanel.Dock="Left" Text=" - " />
                <TextBlock DockPanel.Dock="Right" Text="{Binding Description}" />
            </DockPanel>
        </DataTemplate>
    </ComboBox.ItemTemplate>
</ComboBox>

绑定到这个列表: private List<ImageFormatModel> imageFormats = new List<ImageFormatModel>();

public MainWindow()
{
    ComboBoxImages.ItemsSource = imageFormats;
}

对象 ImageFormatModel 由两个字符串组成:

public class ImageFormatModel
{
    public string Extension { get; set; }
    public string Description { get; set; }
}

select编辑的项目是否只显示扩展名,但在下拉菜单中两者都显示?

两个值都应显示在此菜单中:

但是如果我 select 一个,只有扩展名应该是可见的。不是这样的:

您可以将 StyleDataTrigger 应用于要隐藏的 TextBlock 元素:

<DataTemplate>
    <DockPanel>
        <DockPanel.Resources>
            <Style x:Key="tbStyle" TargetType="TextBlock">
                <Style.Triggers>
                    <DataTrigger Binding="{Binding RelativeSource={RelativeSource AncestorType=ComboBoxItem}}" Value="{x:Null}">
                        <Setter Property="Visibility" Value="Collapsed"/>
                    </DataTrigger>
                </Style.Triggers>
            </Style>
        </DockPanel.Resources>
        <TextBlock DockPanel.Dock="Left" Text="{Binding Extension}" />
        <TextBlock DockPanel.Dock="Left" Text=" - " Style="{StaticResource tbStyle}" />
        <TextBlock DockPanel.Dock="Right" Text="{Binding Description}" Style="{StaticResource tbStyle}" />
    </DockPanel>
</DataTemplate>