当DataContext为ViewModel时,将CommandParameter绑定到本地项

本文关键字:绑定 CommandParameter DataContext ViewModel | 更新日期: 2023-09-27 18:03:25

我的命令在我的ViewModel中。我需要传递我的菜单项嵌套的DataGrid。这怎么可能?

<MenuItem Header="Delete item/s" Command="{Binding RemoveHistoryItem}" CommandParameter="{Binding ElementName=HistoryDataGrid}">

当DataContext为ViewModel时,将CommandParameter绑定到本地项

你绝对不应该把这个元素发送回你的ViewModel(就像Jeffery说的)。尝试将需要的DataGrid属性绑定到ViewModel,然后在命令处理程序中访问它们。

我使用了一个按钮来说明,但这将以同样的方式适用于您的菜单项。

ViewModel:

public class ViewModel : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;
    private void OnPropertyChanged(string propertyName)
    {
        if (this.PropertyChanged != null)
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }
    public ICommand RemoveHistoryItemCommand { get; private set; }
    private HistoryItem _selectedHistoryItem;
    public HistoryItem SelectedHistoryItem { get { return _selectedHistoryItem; } set { _selectedHistoryItem = value; OnPropertyChanged("SelectedHistoryItem"); } }
    private ObservableCollection<HistoryItem> _historyItems = new ObservableCollection<HistoryItem>();
    public ObservableCollection<HistoryItem> HistoryItems { get { return _historyItems; } set { _historyItems = value; OnPropertyChanged("HistoryItems"); } }

    public ViewModel()
    {
        this.RemoveHistoryItemCommand = new ActionCommand(RemoveHistoryItem);
        this.HistoryItems.Add(new HistoryItem() { Year = "1618", Description = "Start of war" });
        this.HistoryItems.Add(new HistoryItem() { Year = "1648", Description = "End of war" });
    }
    // command handler
    private void RemoveHistoryItem()
    {            
        if (this.HistoryItems != null)
        {
            HistoryItems.Remove(this.SelectedHistoryItem);
        }
    }
}
public class HistoryItem
{
    public string Year { get; set; }
    public string Description { get; set; }
}
public class ActionCommand : ICommand
{
    public event EventHandler CanExecuteChanged;
    public Action _action;
    public ActionCommand(Action action)
    {
        _action = action;
    }
    public bool CanExecute(object parameter) { return true; }
    public void Execute(object parameter)
    {
        if (CanExecute(parameter))
            _action();
    }
}
Xaml:

<Window.DataContext>
    <local:ViewModel />
</Window.DataContext>

<StackPanel>
    <DataGrid ItemsSource="{Binding HistoryItems}" SelectedItem="{Binding SelectedHistoryItem, Mode=TwoWay}" />
    <Button Content="Remove selected item" Command="{Binding RemoveHistoryItemCommand}" HorizontalAlignment="Left" />
</StackPanel>