I have ListView and i am trying to bind command to ContextMenu of ListView.
<ListView x:Name="listView1" ItemsSource="{Binding Path=Persons}">
<ListView.Resources>
<ContextMenu x:Key="ItemContextMenu">
<MenuItem Header="Add" />
<MenuItem Header="Edit"/>
<Separator/>
<MenuItem Header="Delete" Command="{Binding Msg}" />
</ContextMenu>
</ListView.Resources>
<ListView.ItemContainerStyle>
<Style TargetType="ListViewItem">
<!--<EventSetter Event="PreviewMouseLeftButtonDown" />--><!--Handler="OnListViewItem_PreviewMouseLeftButtonDown" />-->
<Setter Property="ContextMenu" Value="{StaticResource ItemContextMenu}"/>
<Setter Property="HorizontalContentAlignment" Value="Stretch" />
</Style>
</ListView.ItemContainerStyle>
<ListView.View>
<GridView>
<GridViewColumn Header="Name" DisplayMemberBinding="{Binding Path=Name}" />
<GridViewColumn Header="Sur Name" DisplayMemberBinding="{Binding Path=SurName}" />
<GridViewColumn Header="Age" DisplayMemberBinding="{Binding Path=Age}" />
</GridView>
</ListView.View>
</ListView>
<Button Content="Message" Command="{Binding Msg}" />
Binding to Button works well but when i click to delete item in ContextMenu, command is not working! Why?
Your problem is related to using bindings in resources. They normally don't work unless you are using something like {Binding Path=Value,Source={x:Static Some.StaticProperty}}
. In order for ElementName
or DataContext
bindings to work you need to resort to help of ElementSpy
and DataContextSpy
. In your particular case if you are relying on DataContext
binding, your XAML should look like this:
<ListView.Resources>
<DataContextSpy x:Name="spy" />
<ContextMenu x:Key="ItemContextMenu">
<MenuItem Header="Add" />
<MenuItem Header="Edit"/>
<Separator/>
<MenuItem Header="Delete" Command="{Binding DataContext.Msg,Source={StaticResource spy}}" />
</ContextMenu>
</ListView.Resources>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.