【问题标题】:Bind Header of WPF ContextMenu绑定WPF ContextMenu的Header
【发布时间】:2013-07-09 13:52:27
【问题描述】:

我在这里遇到了 TreeView-Binding 和 ContextMenu 的问题:Selected TreeViewItem is null

现在我遇到了这个问题:我有 ContextMenu

<TreeView.ContextMenu>
    <ContextMenu x:Name="MyContext" ItemsSource="{Binding OCContext}" DisplayMemberPath="Text"/>
</TreeView.ContextMenu>

(图片显示了我的 ContextMenu 的样子,不要介意 tabItem...)。

如您所见,它只是 ContetMenu,没有 MenuItem!如果用户点击关闭,我想在我的 ViewModel 中做一些事情(提出命令?)。我也想知道他点击了哪个按钮/菜单。 Menus 的数量是动态的,因为它的 ItemsSource 正在被绑定。

这是我的视图模型:

private ObservableCollection<T_Antwort> _occontext;
public ObservableCollection<T_Antwort> OCContext
{
    get
    {
        if (_occontext == null)
            _occontext = new ObservableCollection<T_Antwort>();
        return _occontext;
    }
    set
    {
        _occontext = value;
        RaisePropertyChanged(() => OCContext);
    }
}

所以我要做的就是将 ContextMenu(“项目”Close 和 CloseOtherThankThis)绑定到我的 ViewModel,所以当用户点击其中一个时,我想在我的 ViewModel 中访问它们。这意味着我不想一个一个地绑定它们,我想以某种方式获取一个事件(ContextMenuItemClicked(?))被调用并在我的 ViewModel 中使用它。

顺便说一句。在 ContextMenu 下使用 MenuItem 将创建另一个“菜单文件夹”,所以它会是

" " -> 关闭

" " -> CloseOtherThankThis

而且我不希望它看起来像这样。

编辑:我目前得到这样的项目:

    private void MyContext_PreviewMouseDown(object sender, MouseButtonEventArgs e)
    {
        System.Windows.Controls.Primitives.MenuBase s = sender as System.Windows.Controls.Primitives.MenuBase;
        ItemCollection ic = s.Items;
        T_Antwort SelectedItem = (T_Antwort)ic.CurrentItem;
    }

有没有可能通过绑定获取选中项?

【问题讨论】:

    标签: c# wpf binding treeview contextmenu


    【解决方案1】:

    不知道你有没有试过,但是上下文菜单有一个 PlacementTarget,它为你提供了包含上下文菜单的对象。

    在我的一个项目中,我做了这样的事情:

     <MenuItem ...    Visibility="{Binding RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type ContextMenu}},Path=PlacementTarget.SelectedItem
    

    【讨论】:

    • 谢谢,但我不知道应该在哪里使用它。我已经用 MenuItem 和一个 CommandBinding 尝试过,上面作为 CommandParameter,但是没有执行命令?.. Command="{Binding asd}" CommandParameter="{Binding RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type ContextMenu}},Path=PlacementTarget.SelectedItem}",VM asd = new RelayCommand&lt;object&gt;(asdexecute);。它也是第二个节点,所以 MenuItem 并不适合。
    • 我不知道 mvvm...对不起...我说的是传统的 wpf。如果你想要一个例子,我可以给你一个传统 wpf 的完整例子。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-07-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-30
    • 1970-01-01
    相关资源
    最近更新 更多