Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
590 views
in Technique[技术] by (71.8m points)

c# wpf - cannot set both DisplayMemberPath and ItemTemplate

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>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...