为什么这个 ComboBox 直接将 SelectedItem 渲染为内容,而不是使用 ItemTemplate?

问题描述 投票:0回答:1

我有一个显示项目列表的组合框。我创建了一个转换器来从该对象类型映射到字符串值。

        <ComboBox ItemsSource="{Binding SelectedDrawing.Icons}" Name="TrackElementSelector" SelectedItem="{Binding SelectedElement}">
            <ComboBox.ItemTemplate>
                <DataTemplate>
                    <TextBlock Text="{Binding Path=., Converter={StaticResource LayoutElementToStringConverter}}" />
                </DataTemplate>
            </ComboBox.ItemTemplate>
        </ComboBox>

问题是,当我选择/单击 ComboBox 中的值时,ComboBox 直接呈现 SelectedItem(它是在我的项目中其他地方定义的控件)。因此,例如,想象一下在单击组合框上的字符串元素“Button”后看到一个文字按钮。我不想要这种行为。

为什么这里没有使用 ItemTemplate?似乎 ItemTemplate 仅在选择值之前才使用。

c# .net wpf xaml combobox
1个回答
0
投票

此显示行为由组合框的

SelectionBoxItemTemplate
属性控制,而不是由
ItemTemplate
控制。

默认情况下,未设置

SelectionBoxItemTemplate
,因此 ComboBox 会尝试直接显示
SelectedItem
。在您的情况下,似乎
SelectedItem
是一个控件(如按钮),因此它呈现该控件。

要解决此问题,您可以将 ComboBox 的

SelectionBoxItemTemplate
设置为与您的
ItemTemplate
相同。

具体操作方法如下:

<ComboBox ItemsSource="{Binding SelectedDrawing.Icons}" Name="TrackElementSelector" SelectedItem="{Binding SelectedElement}">
    <ComboBox.ItemTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding Path=., Converter={StaticResource LayoutElementToStringConverter}}" />
        </DataTemplate>
    </ComboBox.ItemTemplate>
    <!-- Set the SelectionBoxItemTemplate to control how the selected item appears -->
    <ComboBox.SelectionBoxItemTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding Path=., Converter={StaticResource LayoutElementToStringConverter}}" />
        </DataTemplate>
    </ComboBox.SelectionBoxItemTemplate>
</ComboBox>

通过设置

SelectionBoxItemTemplate
,您可以确保所选项目也使用指定的
DataTemplate
进行显示,从而确保您的转换器也用于所选项目。

© www.soinside.com 2019 - 2024. All rights reserved.