加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c#wpf – 无法同时设置DisplayMemberPath和ItemTemplate

发布时间:2020-12-15 18:10:46 所属栏目:百科 来源:网络整理
导读:我想在listboxItem中添加工具提示,但是当有DisplayMemberPath时它会启动问题.错误信息说:无法同时设置DisplayMemberPath和ItemTemplate.当我删除DisplayMemberPath时,每个列表项中的工具提示都有效.但我不想删除DisplayMemember因为我需要它.如何解决这个问
我想在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>

解决方法

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路径并使用DataTemplate的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>

编辑

如果要设置工具提示但保留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可以阻止数据模板中的任何复杂绑定.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读