动态加载的menuitem上的绑定命令

时间:2016-03-10 19:06:01

标签: c# wpf mvvm

我成功填充了一个包含汽车列表的menuitem。我希望menuitem中的每辆车都能够发出命令" RemoveCarCommand"。在一个动态加载的汽车(或任何东西)的菜单上,我知道我需要为menuitem中的每辆车分配命令,但我无法弄明白XAML这样做。有人可以帮忙吗?

<MenuItem Header="Remove Car" ItemsSource="{Binding AvailableCars}">
    <MenuItem.ItemContainerStyle>
        <Style>
            <Setter Property="MenuItem.Command" Value="{Binding RemoveCarCommand, RelativeSource={RelativeSource AncestorType={x:Type ContextMenu}}}"/>
        </Style>
    </MenuItem.ItemContainerStyle>
</MenuItem>

1 个答案:

答案 0 :(得分:0)

我认为你在考虑你的问题,如果每个菜单项只是在另一个&#34; car&#34;上执行相同的任务,你可以将它们全部指向相同的事件处理程序以便点击然后访问datacontext以找出哪一个被点击,从而删除哪辆车。

private void removeCar(object sender, EventArgs e)
{
    Car car = ((sender as Button).DataContext as Car);

    car.remove();
    //OR
    CarsList.Remove(car);
}
CB中的

public class RelayCommand : ICommand
{
    #region Fields

    readonly Action<object> _execute;
    readonly Predicate<object> _canExecute;

    #endregion // Fields

    #region Constructors

    /// <summary>
    /// Creates a new command that can always execute.
    /// </summary>
    /// <param name="execute">The execution logic.</param>
    public RelayCommand(Action<object> execute)
        : this(execute, null)
    {
    }

    /// <summary>
    /// Creates a new command.
    /// </summary>
    /// <param name="execute">The execution logic.</param>
    /// <param name="canExecute">The execution status logic.</param>
    public RelayCommand(Action<object> execute, Predicate<object> canExecute)
    {
        if (execute == null)
            throw new ArgumentNullException("execute");

        _execute = execute;
        _canExecute = canExecute;
    }

    #endregion // Constructors

    #region ICommand Members

    [DebuggerStepThrough]
    public bool CanExecute(object parameters)
    {
        return _canExecute == null ? true : _canExecute(parameters);
    }

    public event EventHandler CanExecuteChanged
    {
        add { CommandManager.RequerySuggested += value; }
        remove { CommandManager.RequerySuggested -= value; }
    }

    public void Execute(object parameters)
    {
        _execute(parameters);
    }

    #endregion // ICommand Members
}

如果您绝对必须使用MVVM绑定命令,那么您需要:

public class Car
{
    private ICommand _ClickCommand;
    public ICommand ClickCommand
    {
        get
        {
            if (_ClickCommand == null)
            {
                _ClickCommand = new RelayCommand(param => this.Click(param, EventArgs.Empty));
            }
            return _ClickCommand;
        }
    }
}

然后在您的班级obj中为Car添加:

                <Menu.ItemContainerStyle>
                    <Style TargetType="{x:Type MenuItem}">
                        <Setter Property="Command" Value="{Binding ClickCommand}"/>
                    </Style>
                </Menu.ItemContainerStyle>

这就是你在WPF中绑定它的方式:

{{1}}