将属性绑定到动态创建的上下文菜单项

时间:2015-04-09 13:03:30

标签: c# wpf xaml contextmenu

我正在尝试制作上下文菜单,其中的项目取决于代码中的某些数据。 所以,我有简单的课程,确定单项菜单

class ContextMenuItem
{
    public string ItemHeader {get; set;}
    public Command ItemAction {get; set;
}

其中Command是ICommand的实现,并存储action,一旦选中此项,将触发该操作。然后我有课,作为DataContext

class SomeClass
{
    public List<ContextMenuItem> ContextMenuItems {get; set;}
    public string SomeProperty {get; set;}
    public string SomeAnotherProperty {get; set;}
}

因此,ContextMenuItems是我在上下文菜单中需要的动作列表,可以使用不同的方法生成。

我正在创建动态上下文菜单,使用此approach

<ContextMenu ItemsSource="{Binding ContextMenuItems}">
    <ContextMenu.ItemContainerStyle>
        <Style TargetType="{x:Type MenuItem}">
            <Setter Property="Command" Value="{Binding ItemAction}"/>
            <Setter Property="Header" Value="{Binding ItemHeader}"/>
        </Style>
    </ContextMenu.ItemContainerStyle>
</ContextMenu>

所以,我怀疑这种方法运作良好。但是,出于某种原因,绑定不是我想要的方式。

<Setter Property="Command" Value="{Binding ItemAction}"/>
<Setter Property="Header" Value="{Binding ItemHeader}"/>

不知何故,此行的数据上下文不是ContextMenuItem,而是SomeClass本身。所以,我可以在这里绑定SomeProperty和SomeAnotherProperty,但不能绑定ItemHeader或ItemAction。这破坏了动态创建上下文菜单的整个想法。

那么,我怎样才能使这个模板将ContextMenuItem识别为其DataContext?

我想要做的事情可以使用DataTemplate完成,但它在MenuItem中提供了MenuItem,这并不好。

更新

涉及ListBox的完整xaml代码

<ListBox Margin="5, 5" Background="White" ItemsSource="{Binding SwitchAgents, UpdateSourceTrigger=PropertyChanged}" HorizontalContentAlignment="Stretch">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <Grid Margin="3,1">
                <Grid.ContextMenu>
                    <ContextMenu ItemsSource="{Binding ContextMenuItems}">
                        <ContextMenu.ItemContainerStyle>
                            <Style TargetType="MenuItem">
                                <Setter Property="Command" Value="{Binding ItemAction}"/>
                                <Setter Property="Header" Value="{Binding ItemHeader}"/>
                            </Style>
                        </ContextMenu.ItemContainerStyle>
                    </ContextMenu>

                </Grid.ContextMenu>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="1*"/>
                    <ColumnDefinition Width="7*"/>
                </Grid.ColumnDefinitions>
                <CheckBox IsChecked="{Binding Enabled, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" Margin="0,3"/>
                <TextBlock Text="{Binding ObjectName}" Grid.Column="1" Margin="0,2"/>
            </Grid>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

2 个答案:

答案 0 :(得分:2)

这项工作有一个偷偷摸摸的伎俩。通常情况下,我只是在绑定中使用RelativeSource来使其与DataContext进行隧道连接。问题是ContextMenu并不位于可视树层次结构中,因此RelativeSource没有任何内容可供查找。

此处概述了解决方案: http://www.thomaslevesque.com/2011/03/21/wpf-how-to-bind-to-data-when-the-datacontext-is-not-inherited

将此类复制/粘贴到您的项目中:

public class BindingProxy : Freezable
{
    #region Overrides of Freezable

    protected override Freezable CreateInstanceCore()
    {
        return new BindingProxy();
    }

    #endregion

    public object Data
    {
        get { return (object)GetValue(DataProperty); }
        set { SetValue(DataProperty, value); }
    }

    // Using a DependencyProperty as the backing store for Data.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty DataProperty =
        DependencyProperty.Register("Data", typeof(object), typeof(BindingProxy), new UIPropertyMetadata(null));
}

然后在Window / UserControl / top的顶部引用BindingProxy的命名空间:

xmlns:local="clr-namespace:INSERTYOURNAMESPACEHERE"

将BindingProxy作为资源添加到ListBox:

<ListBox.Resources>
    <local:BindingProxy x:Key="proxy" Data="{Binding}" />
</ListBox.Resources>

最后将ContextMenu ItemsSource绑定的Source设置为代理:

<ContextMenu ItemsSource="{Binding Data.ContextMenuItems, Source={StaticResource proxy}}" >

答案 1 :(得分:0)

参考下面的代码。它对我来说很好。

<Window x:Class="BindingListBox_Learning.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="350" Width="525">
<Grid>
    <ListBox Margin="5, 5" Background="White"  ItemsSource="{Binding SwitchAgents, UpdateSourceTrigger=PropertyChanged}" HorizontalContentAlignment="Stretch">
        <ListBox.ItemTemplate>
            <DataTemplate>
                <Grid Margin="3,1">
                    <Grid.ContextMenu>
                        <ContextMenu ItemsSource="{Binding ContextMenuItems}">
                            <ContextMenu.ItemContainerStyle>
                                <Style TargetType="MenuItem">
                                    <Setter Property="Command" Value="{Binding ItemAction}"/>
                                    <Setter Property="Header" Value="{Binding ItemHeader}"/>
                                </Style>
                            </ContextMenu.ItemContainerStyle>
                        </ContextMenu>
                    </Grid.ContextMenu>
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="1*"/>
                        <ColumnDefinition Width="7*"/>
                    </Grid.ColumnDefinitions>
                    <CheckBox IsChecked="{Binding Enabled, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" Margin="0,3"/>
                    <TextBlock Text="{Binding SomeProperty}" Grid.Column="1" Margin="0,2"/>
                </Grid>
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>
</Grid>

 public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        this.DataContext = new MainViewModel();           
    }
}

class MainViewModel
{
    public List<SomeClass> SwitchAgents { get; set; }
    public MainViewModel()
    {
        SwitchAgents = new List<SomeClass>();
        SomeClass obj = new SomeClass();
        obj.SomeProperty = "Test";
        List<ContextMenuItem> lst = new List<ContextMenuItem>();
        lst.Add(new ContextMenuItem() { ItemHeader = "Hi", ItemAction = new BaseCommand(MenuClick) });
        obj.ContextMenuItems = lst;
        SwitchAgents.Add(obj);
    }

    void MenuClick(object obj)
    {
        // Do Menu Click Stuff
    }
}

class ContextMenuItem
{
    public string ItemHeader { get; set; }
    public ICommand ItemAction { get; set; }
}

class SomeClass
{
    public List<ContextMenuItem> ContextMenuItems { get; set; }
    public string SomeProperty { get; set; }
    public string SomeAnotherProperty { get; set; }
}

public class BaseCommand : ICommand
{
    private Predicate<object> _canExecute;
    private Action<object> _method;
    public event EventHandler CanExecuteChanged;

    public BaseCommand(Action<object> method)
        : this(method, null)
    {
    }

    public BaseCommand(Action<object> method, Predicate<object> canExecute)
    {
        _method = method;
        _canExecute = canExecute;
    }

    public bool CanExecute(object parameter)
    {
        if (_canExecute == null)
        {
            return true;
        }

        return _canExecute(parameter);
    }

    public void Execute(object parameter)
    {
        _method.Invoke(parameter);
    }
}

而不是BaseCommand,您可以使用来自PRISM的MVVMLight或DelegateCommand的RelayCommand。