WPF ContextMenu

I am using mvvm in a wpf application. I have ContextMenu inside the list, and when I right-click on the listviewitem, I want the context menu to display the list of contacts.

The following just gives me a context menu with no content. Can someone tell me what I am doing wrong?

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

UPDATE:

I realized I had a specialized collection that caused the wrong binding path.

Thanks.

+3
source share
2 answers

The context menu does not exist in the visual tree of your page, so it does not inherit the data context. Try setting the DataContext directly to ContextMenu.

+2
source

, , .

viewmodel .

:

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

. , .

+1

Source: https://habr.com/ru/post/1708846/


All Articles