WPF MenuItem绑定问题

时间:2015-09-05 13:40:14

标签: c# wpf

我遇到了关于MenuItem Binding的问题,我需要将嵌套对象绑定到MenuItem

public class QuestionType
{
    public string Name { get; set; }

    public ICollection<QuestionType> Types { get; set; }
}

public class ViewModel
{
    public ICollection<QuestionType> QuestionTypes { get; set; }

    public ViewModel()
    {
        QuestionTypes = new List<QuestionType>()
        {
            new QuestionType() { Name="Completion" },
            new QuestionType() { Name="Easy" },
            new QuestionType() { Name="MoreType", Types = new List<QuestionType>()
            {
                new QuestionType() { Name="SingleChoice" },
                new QuestionType() { Name="MultiChoice" },
                new QuestionType() { Name="Blend" },
            } },
        };
    }
}

public partial class CustomMenu : UserControl
{
    public CustomMenu()
    {
        InitializeComponent();
        this.DataContext = new ViewModel();
    }
}

在XAML代码中:

我像这样将它们绑定到MenuItem:

<MenuItem ItemsSource="{Binding QuestionTypes}">
    <MenuItem.Resources>
        <HierarchicalDataTemplate DataType="{x:Type local:QuestionType}" 
                                  ItemsSource="{Binding Types}">
            <TextBlock Text="{Binding Name}"/>
        </HierarchicalDataTemplate>
        <DataTemplate DataType="{x:Type local:QuestionType}">
            <TextBlock Text="{Binding Name}"/>
        </DataTemplate>
    </MenuItem.Resources>
</MenuItem>

当我运行我的项目时,发生了异常。 其他信息:Set property 'System.Windows.ResourceDictionary.DeferrableContent' threw an exception.

另外: 我需要为菜单项添加点击事件,如

<MenuItem.Resources>
 ...
</MenuItem.Resources>
<MenuItem.ItemContainerStyle>
    <Style TargetType="{x:Type MenuItem}">
        <EventSetter Event="Menu.Click" Handler="MenuItem_Click"/>
    </Style>
</MenuItem.ItemContainerStyle>

它不起作用,我不知道如何解决这个问题。

1 个答案:

答案 0 :(得分:1)

试试这个:

<MenuItem Header="Question Type" ItemsSource="{Binding QuestionTypes}" Click="MenuItem_Click">
    <MenuItem.Resources>
        <HierarchicalDataTemplate DataType="{x:Type local:QuestionType}" ItemsSource="{Binding Types}">
            <TextBlock Text="{Binding Name}"/>
        </HierarchicalDataTemplate>
    </MenuItem.Resources>
</MenuItem>