簡體   English   中英

將屬性綁定到上下文菜單中動態創建的項目

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

我正在嘗試制作“上下文菜單”,該菜單中的項目取決於代碼中的某些數據。 所以,我有簡單的課堂,確定菜單的單個項目

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

其中Command是ICommand的實現,並存儲操作,一旦選擇此項目,將觸發該操作。 然后我有課,作為DataContext

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

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

我正在使用這種方法創建動態上下文菜單。

<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>

進行這項工作有一個偷偷摸摸的技巧。 通常,我只在綁定中使用RelativeSource使其通過DataContext隧道連接到某個對象。 問題在於ContextMenu不在可視樹層次結構中,因此RelativeSource找不到任何內容。

這里概述了該解決方案: http : //www.thomaslevesque.com/2011/03/21/wpf-how-to-bind-to-data-when-the-datacontext-is-not-herited

將此類復制/粘貼到您的項目中的某個位置:

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 /任何位置的頂部引用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}}" >

請參考下面的代碼。 對我來說很好。

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

可以使用MVVMLight中的RelayCommand或PRISM中的DelegateCommand代替BaseCommand。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM