我通过编写一个从IValueConverter接口实现的转换器来解决这个问题。
如果您想在XAML中看到转换器,需要将其引用到这样的静态资源
<Window.Resources>
<local:myConverter x:Key="myConverter"/>
</Window.Resources>
我的设计;
<Grid>
<DataGrid Name="dgList" Background="LightGray" AutoGenerateColumns="False" IsReadOnly="True">
<DataGrid.Columns >
<DataGridTextColumn Width="100" Header="ID" Binding="{Binding ID}"></DataGridTextColumn>
<DataGridTextColumn Width="100" Header="Batterie" Binding="{Binding Battery}" >
<DataGridTextColumn.ElementStyle>
<Style TargetType="{x:Type TextBlock}">
<Setter Property="Background" Value="{Binding Battery, Converter={StaticResource myConverter}}"></Setter>
</Style>
</DataGridTextColumn.ElementStyle>
</DataGridTextColumn>
<DataGridTextColumn Width="100" Header="Current Use" Binding="{Binding CurrentUse}"></DataGridTextColumn>
<DataGridTextColumn Width="100" Header="Occupancy" Binding="{Binding Occupancy}"></DataGridTextColumn>
</DataGrid.Columns>
</DataGrid>
</Grid>
此绑定会将您的数据电池(10、30、40、80等)发送到转换器。转换器返回一个对象,我们的对象必须是SolidColorBrush才能将其绑定为背景。仅此而已。我就这样解决了
<Setter Property="Background" Value="{Binding Battery, Converter={StaticResource myConverter}}"></Setter>
用于将数据转换为背景的myConverter;
public class myConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
SolidColorBrush clr;
if (int.Parse(value.ToString()) >= 80)
clr = new SolidColorBrush(Colors.Green);
else if (int.Parse(value.ToString()) >= 40)
clr = new SolidColorBrush(Colors.Orange);
else if (int.Parse(value.ToString()) >= 0)
clr = new SolidColorBrush(Colors.Red);
else
clr = new SolidColorBrush(Colors.White);
return clr;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
我为您的示例创建了一个类(如果我错了,我没有看到您的示例抱歉)
public class Class1
{
public int ID { get; set; }
public string Battery { get; set; }
public string CurrentUse { get; set; }
public string Occupancy { get; set; }
public static List<Class1> myList = new List<Class1>()
{
new Class1() {ID = 1, Battery = "70", CurrentUse = "xxxx", Occupancy = "xxxx" },
new Class1() {ID = 2, Battery = "100", CurrentUse = "xxxx", Occupancy = "xxxx" },
new Class1() {ID = 3, Battery = "10", CurrentUse = "xxxx", Occupancy = "xxxx" },
new Class1() {ID = 4, Battery = "50", CurrentUse = "xxxx", Occupancy = "xxxx" },
new Class1() {ID = 5, Battery = "80", CurrentUse = "xxxx", Occupancy = "xxxx" },
new Class1() {ID = 6, Battery = "40", CurrentUse = "xxxx", Occupancy = "xxxx" },
new Class1() {ID = 7, Battery = "39", CurrentUse = "xxxx", Occupancy = "xxxx" }
};
}
在主窗口上
private void Window_Loaded(object sender, RoutedEventArgs e)
{
dgList.ItemsSource = Class1.myList;
}
我的项目截图。