c# wpf - cannot set both DisplayMemberPath and ItemTemplate

天涯浪子 提交于 2019-11-30 04:20:26

问题


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?

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

回答1:


DisplayMemberPath is, in effect, a template for a single property, shown in a TextBlock. If you set:

<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 DisplayMemberPath path and use the value in your 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 ToolTip but keep the DisplayMemberPath, you can do it at the 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 DisplayMemberPath stops you from any complex binding in your data template.



来源:https://stackoverflow.com/questions/18273415/c-sharp-wpf-cannot-set-both-displaymemberpath-and-itemtemplate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!