来自ObservableCollection的动态菜单:将项目作为参数传递

时间:2019-03-13 17:23:10

标签: c# wpf

我正在尝试根据菜单中的单击更改主ViewModel中的属性,该菜单由对象列表填充。

ViewModel

public class MyViewModel : ObservableObject
{
    /// <summary>
    /// Private field for products
    /// </summary>
    private ObservableCollection<Product> products;

    /// <summary>
    /// Private field for the product
    /// </summary>
    private Product product;

    /// <summary>
    /// Gets or sets the Product
    /// </summary>
    public Product Product
    {
        get => this.product;
        set
        {
            this.product = value;
            this.RaisePropertyChangedEvent("Product");
        }
    }

    /// <summary>
    /// Gets or sets a collection of Products
    /// </summary>
    public ObservableCollection<Product> Products
    {
        get => this.plant;
        set
        {
            this.plant = value;
            this.RaisePropertyChangedEvent("Products");
        }
    }

    public ICommand ChangeProduct => new DelegateCommand(p => this.SetProduct((Product)p), p => p is Product);

    private void SetProduct (Product product) => this.Product = product;
}

我正在尝试通过点击Product中的MenuItem来更改Menu

<Menu Grid.Row="0" Background="White">
    <MenuItem Header="Products">
        <MenuItem Name="ProductMenu" Header="Change Product" ItemsSource="{Binding Products}" DisplayMemberPath="Name" Command="{Binding ChangeProduct}" CommandParameter="{Binding ElementName=ProductMenu}"/>
    </MenuItem>
</Menu>

但是,这不起作用。如何在我的ViewModel中将附加到被点击的生成的Product的{​​{1}}作为参数绑定?

2 个答案:

答案 0 :(得分:0)

Xaml可能是这样的:

<Menu Grid.Row="0" Background="White">
   <MenuItem Header="Products"   >
       <MenuItem Name="ProductMenu" Header="Products"  ItemsSource="{Binding Products}"  DisplayMemberPath="Name" >
                    <MenuItem.ItemContainerStyle>
                        <Style TargetType="MenuItem">
                             <Setter Property="Command" Value="{Binding  ElementName=ProductMenu, Path=DataContext.ChangeProduct}"/>
                            <Setter Property="CommandParameter" Value="{Binding}"/>
                        </Style>
                    </MenuItem.ItemContainerStyle>
                </MenuItem>

   </MenuItem>
</Menu>

答案 1 :(得分:0)

只需将CommandParameter绑定更改为CommandParameter="{Binding}",即删除路径:

<MenuItem Name="ProductMenu"
        Header="Change Product" 
        ItemsSource="{Binding Products}" 
        DisplayMemberPath="Name" 
        Command="{Binding ChangeProduct}" 
        CommandParameter="{Binding}"/>