我可以通过下面的C#代码来改变数据单元的背景-
private void Retrieve_rows(object item)
{
DataRow row = mygrid.GetContainerFromItem(item) as DataGrid.DataRow;
if (row != null)
{
SolidColorBrush redColor = new SolidColorBrush (Colors.Red);
foreach (DataGrid.DataCell cell in row.Cells)
{
var dc = ((System.Windows.FrameworkElement)(((DataGrid.Cell)(cell)).ParentRow)).DataContext;
// get my custom object and change color if IsBlank value is set to true
MyRowObject rowObject = dc as MyRowObject;
for (int counter = 0; counter < rowObject.values.Count; counter++)
{
if (rowObject.values[counter].IsBlank == true)
row.Cells[counter].Background = redColor;
}
}
return;
}
}
}但是使用这些代码,应用程序性能会在很大程度上降低。有没有办法将上面的代码转换成XAML触发器/或任何其他方法来提高网格的性能。
发布于 2012-01-06 23:49:14
由于需要两个动态值来确定单元格的背景颜色(ColumnIndex和ValuesList),因此需要使用接受这两个值并返回一种颜色的MultiConverter。
例如,
if ValueList[ColumnIndex].IsBlank)
Return Colors.Red; // Might be Brushes.Red too, can't remember
else
Return Colors.White;然后,可以将触发器隐式应用于样式未指定键的所有DataGridCells
<Style TargetType="{x:Type DataGridCell}">
<Setter Property="Background">
<Setter.Value>
<MultiBinding Converter="{StaticResource MyMultiConverter}">
<Binding Path="Column.DisplayIndex" RelativeSource="{RelativeSource Self}" />
<Binding Path="ValueList" />
</MultiBinding>
</Setter.Value>
</Setter>
</Style>我可能在MultiBinding的Column.DisplayIndex绑定中使用了错误的RelativeSource语法,但是绑定应该指向Self,即DataGridCell
发布于 2012-01-06 23:03:33
欢迎来到WPF世界;)
你可以试试这个:
<DataGrid Name="myGrid">
<DataGrid.Columns>
<DataGridTextColumn Header="Col1" Binding="{Binding Col1}" />
<DataGridTextColumn Header="Col2" Binding="{Binding Col2}" />
</DataGrid.Columns>
<DataGrid.CellStyle>
<Style TargetType="{x:Type DataGridCell}">
<Setter Property="Background" Value="Red" />
</Style>
</DataGrid.CellStyle>
</DataGrid>干杯,
Sebi
发布于 2012-01-06 23:14:06
我认为你不能,因为数据网格只定义了结构,而不是样式。
我在网格单元格中使用矩形。
<Rectangle Grid.Column="1" Grid.Row="1" Fill="Red"></Rectangle>
<TextBox Grid.Column="1" Grid.Row="1" Background="Transparent" Text="test"></TextBox>https://stackoverflow.com/questions/8759584
复制相似问题