WPF 根据绑定值调用不同的样式

       有些情况,元素的样式要随着绑定的值不而改变,下面为实现方法:

 
        样式:
        p,s. 最好定义为全局样式,不然之后用到的转换器可能会找不到.
 
        <Style x:Key="border1" TargetType="Border">
            <Setter Property="Background">
                <Setter.Value>
                    <LinearGradientBrush>
                        <GradientStop Color="#f00" Offset="0.5"/>
                        <GradientStop Color="#fff" Offset="1"/>
                    </LinearGradientBrush>
                </Setter.Value>
            </Setter>
        </Style>
        <Style x:Key="border2" TargetType="Border">
            <Setter Property="Background">
                <Setter.Value>
                    <LinearGradientBrush>
                        <GradientStop Color="#00f" Offset="0.5"/>
                        <GradientStop Color="#fff" Offset="1"/>
                    </LinearGradientBrush>
                </Setter.Value>
            </Setter>
        </Style>
 
        
        转换器:
    
        public class BGConvert : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            int age = (int)value;
            Style style = new Style();
            FrameworkElement fe = new FrameworkElement();
            style = (Style)fe.TryFindResource("border1");
            if (age % 2 == 0)
            {
                style = (Style)fe.TryFindResource("border1");
            }
            else
            {
                style = (Style)fe.TryFindResource("border2");
            }
            return style;
        }
        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }
 
        页面文件:
 
        <Window x:Class="StyleForBG.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:convert="clr-namespace:StyleForBG"
        Title="MainWindow" Height="350" Width="525" Loaded="Window_Loaded">
    <Window.Resources>
        //定义资源
        <convert:BGConvert x:Key="conver"/>        
    </Window.Resources>
    <Grid>
        <ListView x:Name="lvTest" ItemsSource="{Binding}" Width="500" Height="300">
            <ListView.ItemTemplate>
                <DataTemplate>
                                                                              //使用转换器
                    <Border BorderBrush="Black" Style="{Binding StuAge, Converter={StaticResource conver}}" BorderThickness="1" Width="120" Height="60">
                        <TextBlock Text="{Binding StuName}" />
                    </Border>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>
    </Grid>
</Window>
原文地址:https://www.cnblogs.com/Dincat/p/2509043.html