WPF右键菜单

3
我正在使用mvvm在wpf应用程序中。我在listview中有一个ContextMenu,当我右键单击listviewitem时,我希望ContextMenu显示联系人列表。
以下代码只给我一个没有内容的ContextMenu。有谁能告诉我我做错了什么?
<ListView Grid.Row="3"
            ItemsSource="{Binding Path=Phones}"
            SelectedItem="{Binding Phones.SelectedItem}"
            Height="100">
    <ListView.ItemContainerStyle>
        <Style TargetType="{x:Type ListViewItem}">
            <Setter Property="ContextMenu" Value="{StaticResource ContactMenu}"/>
        </Style>
    </ListView.ItemContainerStyle>
    <ListView.View>
        <GridView>
            <GridViewColumn Header="Phone" DisplayMemberBinding="{Binding Path=PhoneNumber, StringFormat=(000) 000-0000}"/>
            <GridViewColumn Header="Type" DisplayMemberBinding="{Binding Path=PhoneType.Type}"/>
            <GridViewColumn Header="Contacts" DisplayMemberBinding="{Binding Path=Contacts.Count}"/>
            <GridViewColumn Header="Notes" DisplayMemberBinding="{Binding Path= Notes.Count}"/>
            <GridViewColumn Header="Priority" DisplayMemberBinding="{Binding Path=Priority}"/>
        </GridView>
    </ListView.View>
</ListView>


<UserControl.Resources>
    <Style TargetType="{x:Type ListViewItem}">
        <Setter Property="Background" Value="{Binding SourceType, Converter={StaticResource SourceGroupConverter}}"/>
    </Style>
    <ContextMenu x:Key="ContactMenu" ItemsSource="{Binding Contacts}" >
        <ContextMenu.ItemTemplate>
            <DataTemplate>
                <MenuItem Header="{Binding Path=FirstName}"/>
            </DataTemplate>
    </ContextMenu>
</UserControl.Resources>

更新:

我找到解决方法了,是由于一个特殊的集合导致绑定路径不正确。

谢谢。


虽然我现在没有答案给你,但看起来你漏掉了一个</ContextMenu.ItemTemplate>。 - Ryan Versaw
2
Jose,我很高兴你解决了这个问题。你能在这里发布解决方案吗,这样我(和其他人)也可以受益于此 :) - Robert Taylor
2个回答

2

上下文菜单不在您页面的可视树中,因此它不会继承数据上下文。尝试直接在ContextMenu上设置DataContext。


1

我一直在等Jose的答案,想知道他是如何绕过这个问题的,但最终我自己解决了它。

对我来说,将模型包装到一个带有访问器的视图模型类中有所帮助。

例如:

ObservableCollection<CtxItemViewModel> ctxItems = new ObservableCollection<CtxItemViewModel>();
CtxItem c = new CtxItem();
c.Name = "Hello World";
ctxItems.Add(new CtxItemViewModel(c));

在ViewModel内部:

public string Name {
   get { return _model.Name; }
   set { _model.Name = value; }
}

添加访问器有助于我的绑定。希望这也能帮助其他人。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接