根据自定义逻辑更新项目样式

时间:2011-04-19 09:53:53

标签: .net wpf xaml

目的是在树状视图中设置项目的样式。样式选择取决于项目的属性。我尝试了两种方法:

  1. 从TreeView.ItemTemplate中的触发器切换项目的样式。问题是你不能从另一种风格中分配风格。

  2. 从ItemContainerStyleSelector切换项目的样式。问题是如果item的属性更新(在表单初始化之后),样式不会更新。 (因为StyleSelector.SelectStyle不会触发)。

1 个答案:

答案 0 :(得分:3)

您可以将Style-property绑定到对象的更改属性,然后使用ValueConverter返回正确的样式,例如当财产是布尔时:

public class StyleSelectionConverter : IValueConverter
{
    public Style OnStyle { get; set; }
    public Style OffStyle { get; set; }

    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        bool input = (bool)value;
        if (input)
        {
            return OnStyle;
        }
        else
        {
            return OffStyle;
        }
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotSupportedException();
    }
}

用法示例:

<ListView.Resources>
    <Style x:Key="OnStyle" TargetType="{x:Type TextBlock}">
        <Setter Property="Background" Value="LightGreen"/>
        <Setter Property="Foreground" Value="Green"/>
    </Style>
    <Style x:Key="OffStyle" TargetType="{x:Type TextBlock}">
        <Setter Property="Background" Value="Pink"/>
        <Setter Property="Foreground" Value="DarkRed"/>
    </Style>
    <local:StyleSelectionConverter x:Key="StyleSelectionConverter"
                                   OnStyle="{StaticResource OnStyle}"
                                   OffStyle="{StaticResource OffStyle}"/>
</ListView.Resources>
...
<GridViewColumn Header="Is Active">
    <GridViewColumn.CellTemplate>
        <DataTemplate>
            <DataTemplate.Resources>
            </DataTemplate.Resources>
            <TextBlock Style="{Binding IsActive, Converter={StaticResource StyleSelectionConverter}}"
                       Text="{Binding IsActive}"/>
        </DataTemplate>
    </GridViewColumn.CellTemplate>
</GridViewColumn>