Tutorial :WPF ContextMenu


I am using mvvm in a wpf app. I have a ContextMenu inside of a listview and when I right click a listviewitem i want a contextmenu to display a list of Contacts.

The following just gives me a contextmenu with no content. Can anyone tell me what I'm 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>  


I figured it out, I had a specialized collection that caused the binding path to be incorrect.



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


I was missing the answer from Jose how he circumvented the problem as well, but was able to figure it out by myself.

For me, wrapping the model into a viewmodel class with accessors helped.

For example:

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

and inside the ViewModel:

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

Adding the accessors helped me with binding. Hope this helps others as well.

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »