【问题标题】:c# wpf - cannot set both DisplayMemberPath and ItemTemplatec# wpf - 不能同时设置 DisplayMemberPath 和 ItemTemplate
【发布时间】:2013-08-16 12:32:14
【问题描述】:

我想在 listboxItem 中添加工具提示,但是当有 DisplayMemberPath 时它开始出现问题。错误信息说:不能同时设置 DisplayMemberPath 和 ItemTemplate。当我删除 DisplayMemberPath 时,每个列表项中的工具提示都在工作。但我不想删除 DisplayMemember,因为我需要它。如何解决这个问题?

               <ListBox x:Name="lstToys" Style="{DynamicResource ListBoxStyle1}"  ItemsSource="{Binding Strings}" DisplayMemberPath="Toys" MouseDoubleClick="lstToys_MouseDoubleClick">
                    <ListBox.ItemTemplate>
                        <DataTemplate>
                            <TextBlock Text="{Binding}" ToolTip="Here is a tooltip"/>
                        </DataTemplate>
                    </ListBox.ItemTemplate>
                </ListBox>

【问题讨论】:

  • 将该路径放入 DataTemplate 绑定中

标签: c# wpf listbox listboxitems


【解决方案1】:

DisplayMemberPath 实际上是单个属性的模板,显示在TextBlock 中。如果你设置:

<ListBox x:Name="lstToys" Style="{DynamicResource ListBoxStyle1}"  
         ItemsSource="{Binding Strings}" DisplayMemberPath="Toys">
</ListBox>

相当于:

<ListBox x:Name="lstToys" Style="{DynamicResource ListBoxStyle1}"  
         ItemsSource="{Binding Strings}">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding Toys}"/>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

您可以简单地删除DisplayMemberPath 路径并使用DataTemplateBinding 中的值:

<ListBox x:Name="lstToys" Style="{DynamicResource ListBoxStyle1}"  
         ItemsSource="{Binding Strings}">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding Toys}" ToolTip="Here is a tooltip!"/>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

编辑

如果您想设置ToolTip 但保留DisplayMemberPath,您可以在ItemContainerStyle 处进行:

<ListBox x:Name="lstToys" Style="{DynamicResource ListBoxStyle1}"  
         ItemsSource="{Binding Strings}" DisplayMemberPath="Toys">
    <ListBox.ItemContainerStyle>
        <Style TargetType="ListBoxItem">
            <Setter Property="ToolTip" Value="Here's a tooltip!"/>
        </Style>
    </ListBox.ItemContainerStyle>
</ListBox>

我建议不要这样做。请记住,使用 DisplayMemberPath 会阻止您在数据模板中进行任何复杂的绑定。

【讨论】:

  • 但我不想删除 DisplayMemberPath,因为它链接到我创建的一些函数。
  • @user235973457 查看我的编辑。如果你有DisplayMemberPath,你仍然不能输入ItemTemplate。如果您需要变得更复杂的模板,您将需要更改您的逻辑(我认为在视图之外使用 DisplayMemberPath 自定义逻辑不是一个好主意)。
  • 它像炸弹一样工作。谢谢你的建议。我会记住这一点:)
  • 也为我工作。非常感谢您节省我的时间。
  • 但这不适用于选定的值,因为选择后我的组合框会显示整个文本,因此它的宽度会增加,因为它是自动的。对所选项目也有帮助吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-09-07
  • 1970-01-01
  • 2013-01-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多