Adding a small, coloured rectangle in DataGrid cell

人盡茶涼 提交于 2021-02-08 13:25:17

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/5474828/adding-a-small-coloured-rectangle-in-datagrid-cell

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!