如何将动态构建列表显示为WPF(MVVM)中菜单项的子菜单?

时间:2014-11-25 19:56:32

标签: wpf xaml submenu

我不知道为什么这不起作用。我的目标是显示与“View”菜单项的命令绑定的菜单项列表。单击“视图”时显示的子菜单将动态构建在视图模型中,并取决于某些其他属性的值。

为什么这不起作用,我该如何解决?

我感谢任何帮助。感谢。

附录:“不起作用”表示单击“查看”时显示屏上没有任何内容。

XAML

    <UserControl x:Class="Nova5.UI.Views.Ink.InkView"
       ..............................

<Grid>
        .........................

    <Menu Grid.Row="3" Height="28" >
         <MenuItem Header="Document">
            <MenuItem Header="Demographics"         Command="{Binding Demographics}" />
            <MenuItem Header="Note Pad"             Command="{Binding NotePad}"  />
        </MenuItem>

        <MenuItem Header="Save"   Command="{Binding Save}" />
        <MenuItem Header="Print"  Command="{Binding Print}" />

        <MenuItem Header="View"   ItemsSource="{Binding SubItems}" >
            <MenuItem.ItemTemplate>                           <*--THIS DOES NOT WORK!
                <DataTemplate>
                    <MenuItem  Header="{Binding DisplayName}"  />
                </DataTemplate>
            </MenuItem.ItemTemplate>
       </MenuItem>               

    </Menu>

</Grid>

在ViewModel中,

    private ObservableCollection<MyMenuItem> subItems;
    public ObservableCollection<MyMenuItem> SubItems
    {
        get { return this.subItems; }
        set { subItems = value; OnPropertyChanged("SubItems"); }
    }

在ViewModel的构造函数中,

 public InkViewModel(...) : base()
    {

        subItems = new ObservableCollection<MyMenuItem>();
        subItems.Add(new MyMenuItem { DisplayName = "My first Menu Item" });
        subItems.Add(new MyMenuItem { DisplayName = "Here I am" });

最后,MyMenuItem是:

         public class MyMenuItem : INotifyPropertyChanged
{
   public MyMenuItem()
    {
        this.subItems = new ObservableCollection<MyMenuItem>();
    }

   private string displayName;
    public string DisplayName 
    {
        get
        {
            return displayName;
        }
        set
        {
            if (displayName != value)
            {
                displayName = value;
                OnPropertyChanged("DisplayName");
            }
        }
    }

    private ObservableCollection<MyMenuItem> subItems;
    public ObservableCollection<MyMenuItem> SubItems
    {
        get { return this.subItems; }
        set { subItems = value; OnPropertyChanged("SubItems"); }
    }


    public event PropertyChangedEventHandler PropertyChanged;

    protected void OnPropertyChanged(string propertyName)
    {
        if (this.PropertyChanged != null)
        {
            this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }
 }

1 个答案:

答案 0 :(得分:0)

似乎您正在将集合设置为局部变量。要使绑定工作,请将集合值设置为属性的公共成员。