WPF ContextMenu绑定
<Window DataContext="{Binding MyViewModelInstance}"> <ListBox ItemsSource="{Binding MyDataItems}"> <ListBox.ContextMenu> <ContextMenu DataContext="{Binding PlacementTarget.DataContext, RelativeSource={RelativeSource Mode=Self}}"> <MenuItem Header="刷新" Command="{Binding DataContext.RefreshCommand, RelativeSource={RelativeSource Mode=Self}}"/> </ContextMenu> </ListBox.ContentMenu> </ListBox> </Window>
ViewModel类:
public class MyViewModel { public ObservableCollection<string> MyDataItems { get; set; } public ICommand RefreshCommand { get; set; } }