2011-10-21 46 views
5

我有一个名为Color的列的DataGrid。使用绑定WPF DataGrid单元格背景

<DataGridTextColumn Header="Color" Binding="{Binding MyColor.Percentage}"/> 

数据网格的的ItemSource是一些对象,具有MyColor属性内。

public class MyColor 
{ 
    Color Background { get; set; } 
    int Percentage { get; set; } 
} 

时的ItemSource设置柱,以Percentage值自动填充。现在我想将此列中每个单元格的背景设置为对应于MyColor.Color属性的颜色。有没有办法使用绑定来做到这一点?像

Background="{Binding MyColor.Color}" 

Color性质的东西是HTML格式#XXXXXXXX(叫html格式的?)。

回答

9

您可以通过CellStyle设置:

<DataGridTextColumn Header="Color" Binding="{Binding MyColor.Percentage}"> 
    <DataGridTextColumn.CellStyle> 
     <Style TargetType="DataGridCell"> 
      <Setter Property="Background" Value="{Binding MyColor.Background}" /> 
     </Style> 
    </DataGridTextColumn.CellStyle> 
</DataGridTextColumn> 

而且你必须改变你的MyColor类有Background物业类型Brush,不Color。或者您可以使用转换器将Color转换为SolidColorBrush

+0

好的,我管理转换输入到SolidColorBrush,但有一个问题。我使用Dispatcher将ItemSource分配给DataGrid,因为我的应用程序的其余部分,当我将XAML代码添加到我的应用程序时,它弹出错误“必须在DependencyObject的同一线程上创建DependencySource” –

相关问题