简体   繁体   English

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

[英]Binding property to dynamicaly created item of context menu

I'm trying to make Context Menu, which will have items depending on some data in code. 我正在尝试制作“上下文菜单”,该菜单中的项目取决于代码中的某些数据。 So, i have simple class, determining single item of menu 所以,我有简单的课堂,确定菜单的单个项目

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

where Command is implementation of ICommand, and stores action, which will be fired once this item is selected. 其中Command是ICommand的实现,并存储操作,一旦选择此项目,将触发该操作。 Then i have class, serving as DataContext 然后我有课,作为DataContext

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

So, ContextMenuItems is list of actions I need in my context menu, which can be generated using different approaches. 因此,ContextMenuItems是我在上下文菜单中需要执行的操作的列表,可以使用不同的方法来生成。

And I'm creating dynamic context menu, using this 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>

So, i was suspecting this to work well. 所以,我怀疑这能很好地工作。 But, for some reason, binding works not the way I want it to. 但是,由于某种原因,绑定的工作方式并非我想要的那样。

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

Somehow, data context for this lines is not ContextMenuItem , but SomeClass itself. 不知何故,此行的数据上下文不是ContextMenuItem ,而是SomeClass本身。 So, i can bind SomeProperty and SomeAnotherProperty here, but not ItemHeader or ItemAction. 因此,我可以在此处绑定SomeProperty和SomeAnotherProperty,但不能绑定ItemHeader或ItemAction。 And this ruins whole idea of dynamicaly created context menu. 这破坏了动态创建上下文菜单的整个想法。

So, how can i make this template recognize ContextMenuItem as its DataContext? 那么,如何使此模板将ContextMenuItem识别为其DataContext?

What i want to do can be accomplished using DataTemplate, but it gives us MenuItem inside MenuItem, and this is not good. 我想做的事可以使用DataTemplate完成,但它在MenuItem内给了我们MenuItem,这不好。

Update 更新资料

Full xaml code involving ListBox 涉及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>

There is a sneaky trick to making this work. 进行这项工作有一个偷偷摸摸的技巧。 Normally I'd just use a RelativeSource in the binding to have it tunnel up to something with a DataContext. 通常,我只在绑定中使用RelativeSource使其通过DataContext隧道连接到某个对象。 The problem is that ContextMenu doesn't sit in the visual tree hierarchy, so RelativeSource has nothing to find. 问题在于ContextMenu不在可视树层次结构中,因此RelativeSource找不到任何内容。

The solution is outlined here: http://www.thomaslevesque.com/2011/03/21/wpf-how-to-bind-to-data-when-the-datacontext-is-not-inherited 这里概述了该解决方案: http : //www.thomaslevesque.com/2011/03/21/wpf-how-to-bind-to-data-when-the-datacontext-is-not-herited

Copy/paste this class into your project somewhere: 将此类复制/粘贴到您的项目中的某个位置:

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));
}

Then reference the namespace of the BindingProxy at the top of your Window/UserControl/whatever: 然后在Window / UserControl /任何位置的顶部引用BindingProxy的名称空间:

xmlns:local="clr-namespace:INSERTYOURNAMESPACEHERE"

Add the BindingProxy as a resource to your ListBox: 将BindingProxy作为资源添加到您的ListBox中:

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

And finally set the Source of your ContextMenu ItemsSource binding to the proxy: 最后将您的ContextMenu ItemsSource绑定的Source设置为代理:

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

Refer below code. 请参考下面的代码。 it is working fine for me. 对我来说很好。

<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);
    }
}

Instead of BaseCommand you use RelayCommand from MVVMLight OR DelegateCommand from PRISM. 可以使用MVVMLight中的RelayCommand或PRISM中的DelegateCommand代替BaseCommand。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM