问题描述
Hi
在WPF应用程序中,我使用的是TreeView,它与源绑定。我正在使用DataTrigger根据特定条件更改TreeViewItem的背景。这里我的DataTrigger代码
Hi
In a WPF application I am using a TreeView and it is bind with a source. I am using a DataTrigger to change the background of TreeViewItem based on certain condition. Here my DataTrigger Code
<DataTrigger Binding="{Binding Id, Converter={StaticResource TreeViewItemBackGroundConverter}}" Value="True">
<Setter Property="Background" Value="Red"/>
<Setter Property="Opacity" Value="0.75"/>
<Setter Property="ToolTip" Value="{Binding Id, Converter={StaticResource ErrorConverter}}"/>
</DataTrigger>
它在加载时效果很好,但现在我想在选择更改或项目属性更改时执行此操作。我想检查我使用上面的数据触发器选择项目的相同条件,并根据我想要更改背景的条件。
我尝试使用SelectedItemChanged事件但无法找到TreeViewItem。我正在为TreeViewItem使用ItemTemplate。我怎么能这样做?
请帮助我。
It Works perfect when loading but now I want to do it on selection change or items property change. I want to check the same condition that I am using with Data Trigger above to selected Item and based on condition I want to change the background.
I tried to use SelectedItemChanged event but not able to find the TreeViewItem. I am using a ItemTemplate for the TreeViewItem. How I can do this?
Please help me.
推荐答案
<treeview.itemcontainerstyle>
<style targettype="{x:Type TreeViewItem}">
<setter property="Background" value="{Binding BackgroundColour, Converter={StaticResource BackgroundToColourConverter},Mode=OneWay}" />
<setter property="IsExpanded" value="{Binding IsExpanded, Mode=TwoWay}" />
<setter property="IsSelected" value="{Binding IsSelected, Mode=TwoWay}" />
</style>
</treeview.itemcontainerstyle>
public class BackgroundToColourConverter : IValueConverter
{
public object Convert(object value, Type targetType,
object parameter, CultureInfo culture)
{
string s = value as string;
Color color;
switch (s)
{
case "Green":
color = Colors.Green;
break;
case "Red":
color = Colors.Red;
break;
default:
color = Colors.White;
break;
}
return new SolidColorBrush(color);
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return null;
}
}
这篇关于如何在TreeView的SelectedItemChanged事件上更改TreeViewItem背景颜色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!