Reputation: 25
I am able to change background of datacell through following C# code -
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;
}
}
}
But with this code, application performance degrades to great extent. Is there any way to convert above code to XAML Triggers / or any other way to improve the performance of the grid.
Upvotes: 0
Views: 1605
Reputation: 132558
Since you need two dynamic values to determine the background color of the cell (ColumnIndex
and the ValuesList
), you'll need to use a MultiConverter
which accepts these two values and returns a color.
For example,
if ValueList[ColumnIndex].IsBlank)
Return Colors.Red; // Might be Brushes.Red too, can't remember
else
Return Colors.White;
The Trigger can then be applied implicitly to all DataGridCells
with a style that doesn't have a Key specified
<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>
I might have the RelativeSource
syntax wrong in the Column.DisplayIndex
binding of the MultiBinding
, however the binding should point to Self
, which is the DataGridCell
Upvotes: 3
Reputation: 68
I think you can't because the datagrid only defines structure not style.
I use rectangles in a grid cell.
<Rectangle Grid.Column="1" Grid.Row="1" Fill="Red"></Rectangle>
<TextBox Grid.Column="1" Grid.Row="1" Background="Transparent" Text="test"></TextBox>
Upvotes: 0
Reputation: 4157
Welcome to the WPF world ;)
You could try this:
<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>
Cheers,
Sebi
Upvotes: 0