简体   繁体   中英

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

I have this ComboBox:

<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>

Which is bound to this list: private List<ImageFormatModel> imageFormats = new List<ImageFormatModel>();

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

The Object ImageFormatModel consists of two strings:

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

Is possible that the selected item shows only the extension but in the dropdown menu both are shown?

Both values should be shown in this menu:

下拉式菜单

But if I select one, only the extension should be visible. Not like this: 在此处输入图像描述

You could apply a Style with a DataTrigger to the TextBlock elements to be hidden:

<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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM