我有一个数据网格填充数据,其中一个列存储项目的ID。如果有行在id中有省略,我需要突出显示它们,例如:row1有id = 40,row2有id = 42,id = 41是missind。我能以某种方式使用datatriggers或类似的东西实现这个吗?
答案 0 :(得分:1)
XAML:
<Window x:Class="WpfApplication4.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:app="clr-namespace:WpfApplication4"
Title="MainWindow" Height="350" Width="525">
<Grid>
<DataGrid ItemsSource="{Binding list}">
<DataGrid.Resources>
<app:MissingRowCheckConverter x:Key="MissingRowCheckConverter" />
<Style TargetType="DataGridRow">
<Style.Triggers>
<DataTrigger Value="True">
<DataTrigger.Binding>
<MultiBinding Converter="{StaticResource MissingRowCheckConverter}">
<Binding RelativeSource="{RelativeSource Self}" Path="Item" />
<Binding RelativeSource="{RelativeSource AncestorType=DataGrid}" Path="ItemsSource" />
</MultiBinding>
</DataTrigger.Binding>
<Setter Property="Background" Value="Red" />
</DataTrigger>
</Style.Triggers>
</Style>
</DataGrid.Resources>
</DataGrid>
</Grid>
</Window>
代码背后:
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace WpfApplication4
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public ObservableCollection<MyData> list { get; set; }
public MainWindow()
{
InitializeComponent();
list = new ObservableCollection<MyData>();
for (int i = 1; i <= 100; i++)
{
if (i == 3)
continue;
MyData d = new MyData() { id = i, name = "Name " + i.ToString() };
list.Add(d);
}
DataContext = this;
}
}
public class MyData
{
public int id { get; set; }
public string name { get; set; }
}
public class MissingRowCheckConverter : IMultiValueConverter
{
#region IMultiValueConverter Members
public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (values.Length > 1)
{
MyData d = values[0] as MyData;
if (d == null)
return false;
ObservableCollection<MyData> list = values[1] as ObservableCollection<MyData>;
if (list != null)
{
// Check if any in the list have id - 1
if (list.Any(aa => aa.id == (d.id - 1)))
return false;
// Check if this is the lowest id
if (!list.Any(aa => aa.id < d.id))
return false;
}
}
return true;
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
#endregion
}
}
截图: