2
我遇到了一個關於MenuItem綁定的問題,我需要將一個嵌套對象綁定到MenuItem
。WPF 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>
它沒有工作,我不知道如何解決這個問題。