0

私のコマンドは私のViewModel内にあります。MenuitemがネストされているDataGridを渡す必要があります。これはどのように可能ですか?

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

1 に答える 1

1

UIElementをViewModelに返送しないでください(Jefferyが述べたように)。必要なDataGridプロパティをViewModelにバインドしてから、コマンドハンドラー内でそれらにアクセスしてみてください。

説明のためにボタンを使用しましたが、これはMenuItemでも同じように機能します。

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>
于 2013-03-10T20:57:21.563 に答える