WPF基于数据类型的设置风格? [英] WPF Setting style based on datatype?
问题描述
这是问题。我绑定一个TreeView与一些不同类型的对象。每个对象都是一个节点,SOME对象有一个名为IsNodeExpanded的属性,当然还有一些没有。这是我的风格:
Here's the problem. I'm binding a TreeView with a few different types of objects. Each object is a node, and SOME objects have a property called IsNodeExpanded, and of course, some others don't. Here's my style:
<Style TargetType="{x:Type TreeViewItem}">
<Setter Property="IsExpanded" Value="{Binding IsNodeExpanded, Mode=TwoWay}" />
</Style>
现在,问题是绑定没有此属性的项目时,我们收到此错误在输出中:
Now, the problem is when binding the items that DON'T have this property, we get this error in the output:
System.Windows.Data Error: 39 : BindingExpression path error: 'IsNodeExpanded' property not found on 'object' ''CompensationChannel' (HashCode=56992474)'. BindingExpression:Path=IsNodeExpanded; DataItem='CompensationChannel' (HashCode=56992474); target element is 'TreeViewItem' (Name=''); target property is 'IsExpanded' (type 'Boolean')
当然我们得到它一吨。所以我试图提出一种方法来根据它所持有的DataType来切换TreeViewItem的样式。任何想法如何做到这一点?
Of course we get it a ton of times. So I'm trying to come up with a way to switch the style of the TreeViewItem based on the DataType it holds. Any idea on how to do this?
一些信息:我不能手动为每个项目,因为我不是在XAML中创建它们,它们是动态创建的来自数据源。
Some info: I can't do it manually for each item because I'm not creating them in XAML, they are created dynamically from a data source.
编辑:我发现这个答案,但它对我来说没有用。
I found this answer but it didn't work for me.
推荐答案
尝试使用 TreeView.ItemContainerStyleSelector
属性与自定义 StyleSelector
类更改样式取决于绑定对象是否具有该属性。
Try using the TreeView.ItemContainerStyleSelector
property with a custom StyleSelector
class which changes the style depending if the bound object has that property or not.
public class TreeItemStyleSelector : StyleSelector
{
public Style HasExpandedItemStyle { get; set; }
public Style NoExpandedItemStyle { get; set; }
public override Style SelectStyle(object item, DependencyObject container)
{
// Choose your test
bool hasExpandedProperty = item.GetType().GetProperty("IsExpanded") != null;
return hasExpandedProperty
? HasExpandedItemStyle
: NoExpandedItemStyle;
}
}
在XAML资源中:
<Style x:Key="IsExpandedStyle" TargetType="{x:Type TreeViewItem}">
<Setter Property="IsExpanded" Value="{Binding IsNodeExpanded, Mode=TwoWay}" />
</Style>
<Style x:Key="NoExpandedStyle" TargetType="{x:Type TreeViewItem}">
</Style>
<x:TreeViewItemStyleSelector x:Key="TreeViewItemStyleSelector"
HasExpandedItemStyle="{StaticResource IsExpandedStyle}"
NoExpandedItemStyle="{StaticResource NoExpandedStyle}" />
在XAML中:
<TreeView ItemsSource="{Binding ...}"
ItemContainerStyleSelector="{StaticResource TreeItemStyleSelector}">
这篇关于WPF基于数据类型的设置风格?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!