在DataGrid单元格中添加一个小的彩色矩形

时间:2011-03-29 15:15:34

标签: .net wpf datagrid

我希望在我的DataGrid中添加一个小的(10x10)矩形作为单元格。我已经在对象中设置了它,我只是想找到一种从代码到我的DataGrid的方法。

这是我的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>

请参阅评论,以便更容易理解我想要的内容。

1 个答案:

答案 0 :(得分:5)

DataGridTextColumn替换为DataGridTemplateColumn。像这样:

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

是的,TemplateCellColour应该是Brush,这是正确的。