Last active
December 18, 2019 06:47
-
-
Save sachintha81/df04102801733cdd6a245c77a86c474b to your computer and use it in GitHub Desktop.
WPF + C# : Display Data and Color Code a DataGrid using Binding
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<Window x:Class="ColorLibrary.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:ColorLibrary" | |
mc:Ignorable="d" | |
Loaded="Window_Loaded" | |
Title="MainWindow" Height="500" Width="400"> | |
<Window.Resources> | |
<Style TargetType="{x:Type DataGridRow}"> | |
<Style.Setters> | |
<Setter Property="Background" Value="{Binding Path=Code}"></Setter> | |
</Style.Setters> | |
</Style> | |
</Window.Resources> | |
<Grid> | |
<!-- Stuff --> | |
<DataGrid Grid.Column="0" Grid.Row="2" Grid.ColumnSpan="2" | |
Name="dgvColors" | |
AutoGenerateColumns="False" | |
Margin="4"> | |
<DataGrid.Columns> | |
<DataGridTemplateColumn Header="#" Width="Auto"> | |
<DataGridTemplateColumn.CellTemplate> | |
<DataTemplate> | |
<TextBlock Text="{Binding Num}" VerticalAlignment="Center" Padding="3"></TextBlock> | |
</DataTemplate> | |
</DataGridTemplateColumn.CellTemplate> | |
</DataGridTemplateColumn> | |
<DataGridTemplateColumn Header="HTML Code" Width="Auto"> | |
<DataGridTemplateColumn.CellTemplate> | |
<DataTemplate> | |
<TextBlock Text="{Binding Code}" VerticalAlignment="Center" Padding="3"></TextBlock> | |
</DataTemplate> | |
</DataGridTemplateColumn.CellTemplate> | |
</DataGridTemplateColumn> | |
<DataGridTemplateColumn Header="Color" Width="*"> | |
<DataGridTemplateColumn.CellTemplate> | |
<DataTemplate> | |
<TextBlock Text="{Binding Color}" VerticalAlignment="Center" Padding="3"></TextBlock> | |
</DataTemplate> | |
</DataGridTemplateColumn.CellTemplate> | |
</DataGridTemplateColumn> | |
</DataGrid.Columns> | |
</DataGrid> | |
</Grid> | |
</Window> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
NOTE
<Setter Property=""Background"" Value=""{Binding Path=Code}""></Setter>
Here, 'Code' is a property in a class which contains the color name to be used to color the cell.
Then we have an ObservableCollection of that class objects. In code behind, you need to set this property (of each item in the ObservableCollection) to the color you need each row to be displayed in.