WPF使用数据触发器,根据数据源范围改变控件样式

转换器

    public class SourceToBooleanConverter : IValueConverter
    {
        // Convert enum [value] to boolean, true if matches [param]
        public object Convert(object value, Type targetType, object param, CultureInfo culture)
        {
            return double.Parse(value.ToString()) > double.Parse(param.ToString());
        }

        // Convert boolean to enum, returning [param] if true
        public object ConvertBack(object value, Type targetType, object param, CultureInfo culture)
        {
            return (bool)value ? param : Binding.DoNothing;
        }
    }

wpf 

//Resources
    <Window.Resources>
        <loc:SourceToBooleanConverter x:Key="sourceToBooleanConverter" />
         <Style x:Key="totalScoreStyle" TargetType="Label">
            <Setter Property="FontSize" Value="24"/>
            <Setter Property="HorizontalAlignment" Value="Left" />
            <Setter Property="VerticalContentAlignment" Value="Center" />
            <Setter Property="FontFamily" Value="思源黑体 CN Regular"/>
            <Style.Triggers>
                <DataTrigger Binding="{Binding Path=TotalScore,Converter={StaticResource sourceToBooleanConverter}, ConverterParameter=160}" Value="true">
                    <Setter Property="Foreground" Value="Red"></Setter>
                </DataTrigger>
                <DataTrigger Binding="{Binding Path=TotalScore,Converter={StaticResource sourceToBooleanConverter}, ConverterParameter=160}" Value="false">
                    <Setter Property="Foreground" Value="Black"></Setter>
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </Window.Resources>

//标签
     <Label Style="{DynamicResource totalScoreStyle}" Grid.Row="0" Grid.Column="1" Content="{Binding TotalScore}" />

上一篇:解决WPF 内部异常 1: IOException: 找不到资源


下一篇:.NetCore WPF 指定一个相对路径的图片,报错“找不到资源”