silverLight: 修改Datagrid选中行的字体颜色

在我的这篇文章: 修改silverlight DataGrid当前选中行及选中列的背景色 提到了如何修改Datagrid选中行的背景色,今天我又遇到了修改选中行的背景色的需求。还是和背景色一样,需要定制模板。

找到 DataGridRow 默认模板中的如下部分:

<localprimitives:DataGridCellsPresenter Grid.Column="1" Name="CellsPresenter" localprimitives:DataGridFrozenGrid.IsFrozen="True" />

CellsPresenter用于指定要将单元格添加到控件的可视化树中的位置,找到这个控件后,以为只要简单修改它的Foreground就OK了,结果这个控件尽然没有这个属性。还好找到一个办法,把CellsPresenter放到ContentControl 里边,直接设置ContentControl 的Foreground便可实现设置修改datagrid row的前景色的需求,修改后的结果如下:

<ContentControl x:Name="DataGridCellsContent" Grid.Column="1" Foreground="Red">
                                    <localprimitives:DataGridCellsPresenter Name="CellsPresenter" localprimitives:DataGridFrozenGrid.IsFrozen="True" />
                                </ContentControl>

 

 

如果要达到动态修改的效果,则可以在VSM中对应的VisualState部分增加修改ContentControl.Foreground的动画,如:要在MouseOver时改变字体颜色为红色,则修改

<vsm:VisualState x:Name="MouseOver"> <Storyboard> <DoubleAnimation Storyboard.TargetName="BackgroundRectangle" Storyboard.TargetProperty="Opacity" Duration="0" To=".5"/> </Storyboard>

为:

<vsm:VisualState x:Name="MouseOver">
                                            <Storyboard>
                                                <DoubleAnimation Storyboard.TargetName="BackgroundRectangle" Storyboard.TargetProperty="Opacity" Duration="0" To=".5"/>

                                                <ColorAnimation Duration="0" Storyboard.TargetName="DataGridCellsContent" Storyboard.TargetProperty="(Control.Foreground).(SolidColorBrush.Color)" To="White"/>
                                            </Storyboard>
                                        </vsm:VisualState>

 

如果Datagrid中的列都是普通的列,则以上改动便可以满足需求,但是在我的Datagrid中,有两列是HyperLink button,这么改了以后,字体颜色还是改不了,我的解决办法是自定义了一个类 DataGridContentControl 继承自 ContentControl ,在DataGridContentControl 添加一个DependencyProperty:ForeColor,在这个DependencyProperty对应的PropertyChanged事件中,将新值赋给父类的Foreground,同时使用VisualTreeHelper类hard code的去查找HyperLink button控件,找到后设置其Foreground。最后将以上模板中的ContentControl 改成DataGridContentControl,属性改为ForeColor即可。

 

Note: 之所以使用DependencyProperty,是因为只有DependencyProperty才可以通过动画,Style的方式去修改值,普通属性是不行的。

 

DataGridContentControl代码

原文地址:https://www.cnblogs.com/ITHelper/p/1768538.html