我有两种对象类型,为简单起见,我将其称为Category和Product。类别可以包含子类别以及产品。产品不包含其他对象 - 它们是树中的叶子。
public class Product
{
public string Name {get; set;}
}
public class Category
{
public IEnumerable<object> Children
{
//return a mixed set of categories and products
}
public bool IsExpanded {get; set;}
public bool IsHighlighted {get; set;}
}
我想以它们在对象图中出现的确切方式在TreeView中显示它们。 e.g。
Category 1
Product
Category 1.1
Category 1.2
Product
Product
Category 2
Category 2.1
Category 2.1.1
Product
等等。我的XAML是
<UserControl xmlns:.....>
<UserControl.Resources>
<Style x:Key="CategoryStyle" TargetType="TreeViewItem">
<Setter Property="IsExpanded" Value="{Binding IsExpanded ,Mode=TwoWay}"/>
<Style.Triggers>
<DataTrigger Binding="{Binding IsHighlighted}" Value="True">
<Setter Property="FontWeight" Value="Bold"/>
</DataTrigger>
</Style.Triggers>
</Style>
<local:TreeItemStyleSelector x:Key="TreeItemStyleSelector" />
</UserControl.Resources>
<Grid>
<TreeView ItemContainerStyleSelector="{StaticResource TreeItemStyleSelector}">
<!-- ItemContainerStyleSelector causes binding errors-->
<TreeView.Resources>
<!-- template for products -->
<DataTemplate DataType="{x:Type local:Product}">
<Button Content="{Binding Name}" Style="{StaticResource ButtonStyle}"/>
</DataTemplate>
<!-- template for categories -->
<HierarchicalDataTemplate DataType="{x:Type local:Category}" ItemsSource="{Binding Children}">
<StackPanel Orientation="Horizontal">
<!-- template omitted here -->
</StackPanel>
</HierarchicalDataTemplate>
</TreeView.Resources>
</TreeView>
</Grid>
</UserControl>
树呈现正确,但我在输出窗口中收到很多绑定错误,称Product
没有名为Children
,IsExpanded
和IsHighlighted
的属性。似乎WPF尝试在产品上应用HierarchicalDataTemplate
有意思,但是当我删除ItemContainerStyleSelector
时,没有引发任何绑定错误。选择器代码非常简单
public class TreeItemStyleSelector : StyleSelector
{
public override System.Windows.Style SelectStyle(object item, DependencyObject container)
{
if(item is Category)
{
return (System.Windows.Style)((FrameworkElement)container).FindResource("CategoryStyle");
}
return null;
}
}
如何防止引发错误?
任何帮助将不胜感激。