我一直在网上搜索标题中的选项,我看到一个例子,第一行是绿色,其他是红色,这是结论:
<DataGrid>
<DataGrid.ItemContainerStyle>
<Style TargetType="DataGridRow">
<Setter Property="Background" Value="LightBlue"/>
<Style.Triggers>
<DataTrigger
Binding="{Binding RelativeSource={RelativeSource Mode=PreviousData}}"
Value="{x:Null}">
<Setter Property="Background" Value="Green"/>
</DataTrigger>
</Style.Triggers>
</Style>
</DataGrid.ItemContainerStyle>
我试图通过编辑到日期时间来改变它,但我不是专家。我有这个
`<DataGrid.ItemContainerStyle>
<Style TargetType="DataGridRow">
<Setter Property="Background" Value="Red" />
<Style.Triggers>
<DataTrigger Binding="{Binding RelativeSource={RelativeSource Mode=PreviousData}}" Value="{x:Static sys:DateTime.Now}">
<Setter Property="Background" Value="Green"/>
</DataTrigger>
</Style.Triggers>
</Style>
`
有人可以帮帮我吗? Thx提前!
答案 0 :(得分:1)
一种方法是使用转换器:
public class StringToColorConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (value.ToString() == "old")
{
var color = (Color)ColorConverter.ConvertFromString("Red");
return color;
}
else if (value.ToString() == "Upcoming")
{
var color = (Color)ColorConverter.ConvertFromString("Green");
return color;
}
return (Color)ColorConverter.ConvertFromString("Black");
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
然后在XAML中:
<Window x:Class="TestWpf.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:TestWpf"
xmlns:conv="clr-namespace:TestWpf.StringToColorConverter"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<conv:StringToColorConverter x:Key="colorConverter" />
</Window.Resources>
<Grid>
<DataGrid>
<DataGrid.RowStyle>
<Style TargetType="DataGridRow">
<Setter Property="Background">
<Setter.Value>
<Binding Path="Reservation" Converter="{StaticResource StringToColorConverter}"/>
</Setter.Value>
</Setter>
</Style>
</DataGrid.RowStyle>
</DataGrid>
</Grid>
</Window>
答案 1 :(得分:0)
下面的XAML假定它绑定的对象是YourItemSource
,它有一个名为Reservation
的属性。如果Reservation
属性的值为 Old ,则会生成行Red
。如果Reservation
的值为即将推出,则会将其设为Green
。
<DataGrid ItemsSource="{Binding YourItemsSource}">
<DataGrid.RowStyle>
<Style TargetType="DataGridRow">
<Style.Triggers>
<DataTrigger Binding="{Binding Reservation}" Value="Old">
<Setter Property="Background" Value="Red"></Setter>
</DataTrigger>
<DataTrigger Binding="{Binding Reservation}" Value="Upcoming">
<Setter Property="Background" Value="Green"></Setter>
</DataTrigger>
</Style.Triggers>
</Style>
</DataGrid.RowStyle>
</DataGrid>
调整名称以与对象和属性名称及值内联。此外,根据值指示您想要的颜色。