1、我们在做工控项目的时候通常设置配方的上下限
这个时候要求OK数在上下限范围之内,否则NG
首先我们绑定一个简单的List用来展示数据,我这里用学生Age来展示
<ListView ItemsSource="{Binding DataList}" Margin="20">
<ListView.View>
<GridView>
<GridViewColumn Width="80" Header="Id" DisplayMemberBinding="{Binding Id}"/>
<GridViewColumn Width="100" Header="名称" DisplayMemberBinding="{Binding Name}"/>
<GridViewColumn Width="200" Header="年龄" DisplayMemberBinding="{Binding Age}"/>
</GridView>
</ListView.View>
</ListView>
2、我们需要年龄在18岁之下是绿色,否则是蓝色的背景
<Window.Resources>
<cvt:RangeToBooleanConverter x:Key="RangeToBooleanConverter"/>
</Window.Resources>
<Grid>
<ListView ItemsSource="{Binding DataList}" Margin="20">
<ListView.ItemContainerStyle>
<Style TargetType="ListViewItem">
<Style.Triggers>
<DataTrigger Binding="{Binding Age, Converter={StaticResource RangeToBooleanConverter}, ConverterParameter='18-100'}" Value="True">
<Setter Property="Background" Value="Green"/>
</DataTrigger>
<DataTrigger Binding="{Binding Age, Converter={StaticResource RangeToBooleanConverter}, ConverterParameter='0-17'}" Value="True">
<Setter Property="Background" Value="Blue"/>
</DataTrigger>
</Style.Triggers>
</Style>
</ListView.ItemContainerStyle>
<ListView.View>
<GridView>
<GridViewColumn Width="80" Header="Id" DisplayMemberBinding="{Binding Id}"/>
<GridViewColumn Width="100" Header="名称" DisplayMemberBinding="{Binding Name}"/>
<GridViewColumn Width="200" Header="年龄" DisplayMemberBinding="{Binding Age}"/>
</GridView>
</ListView.View>
</ListView>
</Grid>
3、接下来我们看自己定义的RangeToBooleanConverter
public class RangeToBooleanConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value != null && value is int intValue && parameter != null && parameter is string rangeString)
{
var range = rangeString.Split('-');
if (range.Length == 2 && int.TryParse(range[0], out int minValue) && int.TryParse(range[1], out int maxValue))
{
return intValue >= minValue && intValue <= maxValue;
}
}
return false;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
标签:object,int,IValueConverter,基础,intValue,用法,range,&&
From: https://www.cnblogs.com/guchen33/p/18004127