WPF菜单项绑定问题

本文关键字:问题 绑定 菜单项 WPF | 更新日期: 2023-09-27 18:11:15

我遇到了一个关于MenuItem绑定的问题,我需要将一个嵌套对象绑定到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>

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

WPF菜单项绑定问题

试试这个:

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