【问题标题】:How do I bind to a context MenuItem header in WPF MVVM?如何绑定到 WPF MVVM 中的上下文 MenuItem 标头?
【发布时间】:2020-02-11 14:03:25
【问题描述】:

我正在尝试关注this answer,了解如何在 WPF 中制作 MVVM 上下文菜单。这听起来很简单:“上下文菜单项的 ItemTemplate 现在可以访问名称、命令以及您可能需要的任何其他内容。”

没有提及更改数据上下文、可视化树等。

这是我的 ViewModel:

public class ViewModel
{
  public class ContextAction : INotifyPropertyChanged
  {
    public string HeaderText;
    public event PropertyChangedEventHandler PropertyChanged;
    public void RaisePropertyChanged(string property)
    {
      PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(property));
    }
  }

  public ObservableCollection<ContextAction> ContextMenuActions { get; set; }

  public ViewModel()
  {
    ContextMenuActions = new ObservableCollection<ContextAction>();
    ContextMenuActions.Add(new ContextAction { HeaderText = "Foo" });
    ContextMenuActions.Add(new ContextAction { HeaderText = "Bar" });
    ContextMenuActions.Add(new ContextAction { HeaderText = "Baz" });
  }
}

...和我的 XAML:

<Window x:Class="WpfApp1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfApp1"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Window.DataContext>
        <local:ViewModel />
    </Window.DataContext>

    <Grid Background="red">
        <Grid.ContextMenu>
            <ContextMenu ItemsSource="{Binding ContextMenuActions}">
                <ContextMenu.ItemTemplate >
                    <DataTemplate DataType="MenuItem">
                        <MenuItem Header="{Binding HeaderText}" />
                    </DataTemplate>
                </ContextMenu.ItemTemplate>
            </ContextMenu>
        </Grid.ContextMenu>
    </Grid>
</Window>

我可以看到项目被添加到上下文菜单中。右键单击网格会生成一个包含三个空白项的菜单。但是,标题绑定不起作用(每个菜单项都是空白的)。我是否错过了我链接的答案中的某些内容?我需要制作某种代理类as mentioned here吗?对于像制作上下文菜单这样的简单任务来说,这似乎相当复杂,甚至在我链接到的第一个答案中都没有暗示。

【问题讨论】:

    标签: c# wpf mvvm contextmenu


    【解决方案1】:

    您只能绑定到属性,不能绑定到字段

    public string HeaderText {get; set;}
    

    【讨论】:

    • 天哪。我知道。我觉得好傻感谢您花时间回答!
    • 谢谢,我想你该休息一下了 :)
    猜你喜欢
    • 1970-01-01
    • 2017-05-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-11
    • 1970-01-01
    • 2013-01-23
    • 2021-12-31
    相关资源
    最近更新 更多