Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding a small, coloured rectangle in DataGrid cell

Tags:

.net

wpf

datagrid

I am looking to add a tiny (10x10) rectangle as a cell in my DataGrid. I already have it set in the object I'm just looking for a way to get it from the code into my DataGrid.

This is my DataGrid XAML:

<DataGrid Name="dataGrid1" Grid.Row="2" AutoGenerateColumns="False" DataContext="{Binding}" HeadersVisibility="Column" 
              HorizontalGridLinesBrush="#ccc" VerticalGridLinesBrush="#ccc" VirtualizingStackPanel.VirtualizationMode="Standard" Background="#FFF6F6F6" CanUserAddRows="False">
        <DataGrid.Resources>
            <ResourceDictionary Source="Pages/DataGridStyle.xaml" />
        </DataGrid.Resources>
        <DataGrid.Columns>
            <!-- In here I would like a datagrid cell that is just a 10x10 box which uses {Binding Path=TemplateCellColour} (templatecellcolour is stored as a brush, is this an issue? -->
            <DataGridTextColumn ElementStyle="{StaticResource CenterTextCell}" Width="0.5*" Binding="{Binding Path=TemplateCellID}" Header="ID"></DataGridTextColumn>
            <DataGridTextColumn ElementStyle="{StaticResource CenterTextCell}" Width="1*" Binding="{Binding Path=CellWidth}" Header="Width"></DataGridTextColumn>
            <DataGridTextColumn ElementStyle="{StaticResource CenterTextCell}" Width="1*" Binding="{Binding Path=CellHeight}" Header="Height"></DataGridTextColumn>
            <DataGridTextColumn ElementStyle="{StaticResource CenterTextCell}" Width="1*" Binding="{Binding Path=CellTop}" Header="Top"></DataGridTextColumn>
            <DataGridTextColumn ElementStyle="{StaticResource CenterTextCell}" Width="1*" Binding="{Binding Path=CellLeft}" Header="Left"></DataGridTextColumn>
        </DataGrid.Columns>
</DataGrid>

Please see the comment for an easier understanding of what I want.

like image 951
Prisoner Avatar asked Mar 29 '11 15:03

Prisoner


1 Answers

Replace DataGridTextColumn with DataGridTemplateColumn. Something like this:

<DataGridTemplateColumn >
    <DataGridTemplateColumn.CellTemplate>
        <DataTemplate>
            <Rectangle Width="10" Height="10" Fill="{Binding TemplateCellColour}" />
        </DataTemplate>
    </DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>

And yes, TemplateCellColour should be a Brush, that is correct.

like image 146
Snowbear Avatar answered Sep 28 '22 13:09

Snowbear