[英]WPF MenuItem Binding Issue
I faced an issue regarding MenuItem Binding, I need to bind a nested object to a MenuItem
.我遇到了一个关于 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();
}
}
In XAML Code:在 XAML 代码中:
I binding them to MenuItem like this way:我像这样将它们绑定到 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>
When I run my project, an exception occurred.当我运行我的项目时,发生了异常。 Additional information:
Set property 'System.Windows.ResourceDictionary.DeferrableContent' threw an exception.
附加信息:
Set property 'System.Windows.ResourceDictionary.DeferrableContent' threw an exception.
In addition: I need to add click event for Menu Item like另外:我需要为菜单项添加点击事件,例如
<MenuItem.Resources>
...
</MenuItem.Resources>
<MenuItem.ItemContainerStyle>
<Style TargetType="{x:Type MenuItem}">
<EventSetter Event="Menu.Click" Handler="MenuItem_Click"/>
</Style>
</MenuItem.ItemContainerStyle>
It didn't work, I don't know how to solve this issue.它没有用,我不知道如何解决这个问题。
Try this:尝试这个:
<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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.