C# 一种同时使用DisplayMemberPath和ItemTemplate的方法?

C# 一种同时使用DisplayMemberPath和ItemTemplate的方法?,c#,wpf,xaml,contextmenu,itemtemplate,C#,Wpf,Xaml,Contextmenu,Itemtemplate,如下面的XAML所示,我有一个带有标签的列表视图;标签上有一个上下文菜单。ContextMenu位于DataTemplate中,资源由ListView的itemtplate提供。其次,我有一个DisplayMemberPath属性,它链接到我的一个类中的一个方法 <ListView x:Name="TitleList" ItemsSource="{Binding Collections}" ItemTemplate="{DynamicResource Template}" BorderB

如下面的XAML所示,我有一个带有标签的
列表视图
;标签上有一个
上下文菜单
ContextMenu
位于
DataTemplate
中,资源由
ListView
itemtplate
提供。其次,我有一个
DisplayMemberPath
属性,它链接到我的一个类中的一个方法

 <ListView x:Name="TitleList" ItemsSource="{Binding Collections}" ItemTemplate="{DynamicResource Template}" BorderBrush="{x:Null}" DisplayMemberPath="Title">
            <ListView.ItemContainerStyle>
            <Style>
                <Setter Property="FrameworkElement.Margin" Value="20,20,0,0"/>
            </Style>
            </ListView.ItemContainerStyle>
            <ListView.Resources>
                <DataTemplate x:Key="Template">
                    <Label Content="{Binding .}" Width="500" HorizontalAlignment="Left">
                        <Label.ContextMenu>
                            <ContextMenu>
                                <MenuItem Header="Add Question" Click="AddQuestion"/>
                                <MenuItem Header="Edit Title"/>
                                <MenuItem Header="Delete Title"/>
                                <MenuItem Header="Reposition Title"/>
                            </ContextMenu>
                        </Label.ContextMenu>
                    </Label>
                </DataTemplate>
                </ListView.Resources>
        </ListView>
这两个选项都允许我右键单击,它将显示菜单,但字符串显示为
MVVMModel.NewTitleClass

。。。我两者都需要

不,你没有


只需在数据模板中添加一个额外的元素,即可显示每个项目的标题。

删除DisplayMemberPath。您正在使用自定义模板来确定ListViewItem的显示方式。问题在于标签的内容绑定。将其更改为此(如果不起作用,则稍加修改):

另一个选项是,当绑定控件时未指定要显示的属性时,它将使用ToString()结果。如果您没有重写它,它将显示完全限定的类名。因此您可以像这样重写ToString():

public override ToString()
{
   return Title;
}

第一个选项是最好的选择。

旁注-您的代码隐藏事件处理程序不是很好MVVM@Gusdor你是什么意思?这回答了你的问题吗?我将如何实现这一点?
Content="{Binding Title}"
public override ToString()
{
   return Title;
}