日期:2014-05-17 浏览次数:21179 次
View层: <my:DataGrid ......> <my:DataGrid.Columns> <my:DataGridTextColumn Header="AAA" x:Name="AAA" ... HeaderStyle="{StaticResource MyColumnHeadeStyleA}" <my:DataGridTextColumn Header="BBB" x:Name="BBB" ... HeaderStyle="{StaticResource MyColumnHeadeStyleB}" <my:DataGridTextColumn Header="BBB" x:Name="CCC" ... HeaderStyle="{StaticResource MyColumnHeadeStyleC}" </my:DataGrid.Columns> 其中,MyColumnHeadeStyleA,B,C的定义: <Style x:Key="MyColumnHeadeStyleA" TargetType="my:DataGridColumnHeader"> <Setter Property="HorizontalContentAlignment" Value="Center" /> <Setter Property="Background" Value="{Binding Path=HeaderColorA}"/> </Style> <Style x:Key="MyColumnHeadeStyleB" TargetType="my:DataGridColumnHeader"> <Setter Property="HorizontalContentAlignment" Value="Center" /> <Setter Property="Background" Value="{Binding Path=HeaderColorB}"/> </Style> <Style x:Key="MyColumnHeadeStyleC" TargetType="my:DataGridColumnHeader"> <Setter Property="HorizontalContentAlignment" Value="Center" /> <Setter Property="Background" Value="{Binding Path=HeaderColorC}"/> </Style> [Model层] public string HeaderColorA { get{return headerColorA; } set{if (value != headerColorA){headerColorA= value;OnPropertyChanged("HeaderColorA");}} } private string headerColorA= "Red"; ... ...
public System.Windows.Media.Brush HeaderColorA { get{return headerColorA; } set{if (value != headerColorA){headerColorA= value;OnPropertyChanged("HeaderColorA");}} } private System.Windows.Media.Brush headerColorA= Brushes.Red;
------解决方案--------------------
如果楼主的Model是否指Datagrid每行对应的Model,如果是这样的话,肯定不能绑定,DataGridColumnHeader对应的是列,而Model对应的行,每行的Model对应于DatagridRow,DataGridColumnHeader上面是没有数据的,不能绑定
正确的绑定方法是将HeaderStyle里的Background绑定到页面的ViewModel中的HeaderColorA中,绑定代码如下:
<Style x:Key="MyColumnHeadeStyleA" TargetType="DataGridColumnHeader"> <Setter Property="HorizontalContentAlignment" Value="Center" /> <!--向上查找View的数据源进行绑定,也可以通过指定ElementName绑定--> <Setter Property="Background" Value="{Binding Path=HeaderColorA,RelativeSource={RelativeSource FindAncestor,AncestorType=UserControl}}"/> </Style>
------解决方案--------------------
关于绑定颜色,string和Brush都是可以的,我上面的代码在本机测试过的,没问题
------解决方案--------------------