如何在带有 ItemContainerStyle 的 ListView 中使用 DisplayMemberPath?

How to use the DisplayMemberPath in a ListView with an ItemContainerStyle?

ListView控件中,当我想更改ItemContainerStyle时如何使用DisplayMemberPath属性?

我在我的控件 ControlTemplate 中使用了 ListView 控件,而 DisplayMemberPath 属性 是通过 Binding 从控件外部设置的。

<ListView ItemsSource="{TemplateBinding ItemsSource}"
          DisplayMemberPath="{TemplateBinding DisplayMemberPath}">
    <ListView.ItemsPanel>
        <ItemsPanelTemplate>
            <StackPanel Orientation="Horizontal" />
        </ItemsPanelTemplate>
    </ListView.ItemsPanel>
    <ListView.ItemContainerStyle>
        <Style TargetType="{x:Type ListViewItem}">
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="{x:Type ListViewItem}">
                        <StackPanel Orientation="Horizontal">
                            <TextBlock Text="Item:" />
                            <TextBlock Text="{Binding}" />
                            <TextBlock Text=", " />
                        </StackPanel>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>

        </Style>
    </ListView.ItemContainerStyle>
</ListView>

是否可以在XAML中解决这个问题?原文中是怎么解决的ControlTemplate?


我尝试用 MultiValueConverter 解决它,我在其中绑定了 Collection 项和 DisplayMemberPath

<TextBlock>
    <TextBlock.Text>
        <MultiBinding Converter="{StaticResource NameToValueConverter}">
            <Binding />
            <Binding Path="DisplayMemberPath" RelativeSource="{RelativeSource FindAncestor, AncestorType={x:Type ListView}}"/>
        </MultiBinding>
    </TextBlock.Text>
</TextBlock>

有必要吗?还是原来的ListView控件已经解析出来的显示值?

Is it possible to solve it by XAML?

不,您使用 DisplayMemberPathItemTemplate/ItemContainerStyle,但不能同时使用两者。

此外,DisplayMemberPath 属性 应该设置为 string 指定基础数据 属性 的名称 class .它是不是您可以绑定的依赖项属性。