问题
我正在使用数据的 xmlprovider 填充数据网格。加载后,我尝试根据“锁定”行和列的列表为“锁定”列和行着色。这里的“锁定”只是对特定行或列的视觉反馈,不用于进一步计算。虽然数据的加载工作正常,但我尝试了不同的解决方案来设置某些行和列的背景属性,方法是使用数据网格扩展中的扩展循环遍历所有单元格,并取得了喜忧参半的效果。
我尝试为 LOADED 事件中的单元格着色,但这显然并不总是有效。并且没有事件说:“您的数据已加载,先生,现在想做点什么”?
所以我为行和列着色的最后手段可能是使用带有 IMultiValueConverter 类的样式设置器。但我不清楚如何将正确的数据发送到转换器。
编码
这就是我现在所拥有的:
public partial class MainWindow : Window
{
public ObservableCollection<Person> MyDynData { get; set; }
// property representing the locked rows
public List<int> LockedRows { get; set; }
// property representing the locked colums
public List<int> LockedColumns { get; set; }
public MainWindow()
{
InitializeComponent();
MyDynData = Person.GetData();
LockedRows = new List<int>{1,3};
LockedColumns = new List<int>{0};
DataContext = this;
}
}
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
public int Age { get; set; }
public static ObservableCollection<Person>GetData()
{
return new ObservableCollection<Person>
{
new Person {Age = 19, FirstName = "John", LastName = "Gates"},
new Person {Age = 25, FirstName = "Jill", LastName = "Vegas"},
new Person {Age = 48, FirstName = "Bill", LastName = "Bates"},
new Person {Age = 29, FirstName = "Agnes", LastName = "Henderson"},
new Person {Age = 33, FirstName = "Jenny", LastName = "Giggles"}
};
}
}
XAML:
<Window x:Class="DatagridColRowLocker.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:converters="clr-namespace:DatagridColRowLocker"
Title="MainWindow" Height="350" Width="525">
<Grid>
<Grid.Resources>
<converters:CellBackgroundConverter x:Key="CellBackgroundConverter"/>
</Grid.Resources>
<DataGrid ItemsSource="{Binding Path=MyDynData}" AutoGenerateColumns="True">
<DataGrid.Resources>
<Style x:Key="LockedCellStyle" TargetType="DataGridCell">
<Style.Setters>
<Setter Property="Background">
<Setter.Value>
<MultiBinding Converter="{StaticResource CellBackgroundConverter}">
<Binding> ??? the current cell</Binding>
<Binding> ??? List of locked columns</Binding>
<Binding> ??? list of locked rows</Binding>
</MultiBinding>
</Setter.Value>
</Setter>
</Style.Setters>
</Style>
</DataGrid.Resources>
</DataGrid>
</Grid>
</Window>
单元格背景颜色转换器:
class CellBackgroundConverter : IMultiValueConverter
{
public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
{
var cell = (DataGridCell)values[0];
var lockedColumns = (List<int>)values[1];
var lockedRows = (List<int>)values[2];
// how to get the row index?
var isLocked = lockedColumns.Contains(cell.Column.DisplayIndex);
return (isLocked) ? new SolidColorBrush(Colors.LightGray) : new SolidColorBrush(Colors.White);
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
概括
- 如何在 xaml 中正确绑定我的值以使多转换器工作
- 如果我将 datagridcell 传递给转换器,我可以获得 displaycolIndex 但不能获得 rowIndex,这是如何工作的?