c# wpf - 不能同时设置 DisplayMemberPath 和 ItemTemplate
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18273415/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
c# wpf - cannot set both DisplayMemberPath and ItemTemplate
提问by user235973457
I want to add tooltip in listboxItem but it starts problem when there is DisplayMemberPath. Error message said: cannot set both DisplayMemberPath and ItemTemplate. When I removed DisplayMemberPath, tooltip in each list item is working. But i dont want to remove DisplayMemember because i need it. How to solve this problem?
我想在 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>
回答by Simon Belanger
DisplayMemberPathis, in effect, a template for a single property, shown in a TextBlock. If you set:
DisplayMemberPath实际上是单个属性的模板,显示在TextBlock. 如果你设置:
<ListBox x:Name="lstToys" Style="{DynamicResource ListBoxStyle1}"
ItemsSource="{Binding Strings}" DisplayMemberPath="Toys">
</ListBox>
It is equivalent to:
它相当于:
<ListBox x:Name="lstToys" Style="{DynamicResource ListBoxStyle1}"
ItemsSource="{Binding Strings}">
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Toys}"/>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
You can simply remove the DisplayMemberPathpath and use the value in your DataTemplate's Binding:
您可以简单地删除DisplayMemberPath路径并使用您的DataTemplate's 中的值Binding:
<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>
Edit
编辑
If you want to set a ToolTipbut keep the DisplayMemberPath, you can do it at the ItemContainerStyle:
如果您想设置 aToolTip但保留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>
I'd advise against it. Remember that use DisplayMemberPathstops you from any complex binding in your data template.
我建议不要这样做。请记住,使用会 DisplayMemberPath阻止您在数据模板中进行任何复杂的绑定。

