问题
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