Silverlight中用VisualStateManager修改DataGrid选中项前景色求助
如何用VisualStateManager修改DataGrid选中行的字体颜色
我太懂这种“看起来应该不难,实际卡半天”的感觉了!默认的DataGridRow模板确实没直接把Foreground纳入VisualState的控制范围,给你分享个亲测有效的解决思路:
核心思路:修改DataGridRow的模板,给选中状态添加Foreground动画
你可以通过提取默认模板并修改的方式来实现,步骤如下:
- 提取默认DataGridRow模板:在Visual Studio里右键DataGrid→编辑其他模板→编辑DataGridRow的模板→编辑副本;或者用Blend操作更直观,右键DataGridRow→编辑模板→编辑副本,生成默认的模板代码。
- 定位到SelectionStates状态组:在模板的
VisualStateManager.VisualStateGroups里找到SelectionStates,这里包含了选中、未选中、选中未聚焦等状态。 - 给选中状态添加Foreground动画:找到
Selected和SelectedUnfocused这两个状态,在它们的Storyboard里新增针对行内容展示元素的Foreground颜色动画。
完整示例代码
下面是简化后的模板代码,你可以直接参考:
<Style TargetType="{x:Type DataGridRow}"> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="{x:Type DataGridRow}"> <Border x:Name="RowBorder" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}" SnapsToDevicePixels="True"> <VisualStateManager.VisualStateGroups> <!-- 保留其他状态组,比如CommonStates --> <VisualStateGroup x:Name="SelectionStates"> <VisualState x:Name="Unselected"/> <VisualState x:Name="Selected"> <Storyboard> <!-- 原有选中背景动画可以保留 --> <ColorAnimationUsingKeyFrames Storyboard.TargetProperty="(Panel.Background).(SolidColorBrush.Color)" Storyboard.TargetName="RowBorder"> <EasingColorKeyFrame KeyTime="0" Value="#FF3399FF"/> </ColorAnimationUsingKeyFrames> <!-- 新增选中时的字体颜色动画 --> <ColorAnimationUsingKeyFrames Storyboard.TargetProperty="(TextElement.Foreground).(SolidColorBrush.Color)" Storyboard.TargetName="RowContentPresenter"> <EasingColorKeyFrame KeyTime="0" Value="White"/> <!-- 替换成你需要的颜色 --> </ColorAnimationUsingKeyFrames> </Storyboard> </VisualState> <VisualState x:Name="SelectedUnfocused"> <Storyboard> <ColorAnimationUsingKeyFrames Storyboard.TargetProperty="(TextElement.Foreground).(SolidColorBrush.Color)" Storyboard.TargetName="RowContentPresenter"> <EasingColorKeyFrame KeyTime="0" Value="White"/> </ColorAnimationUsingKeyFrames> </Storyboard> </VisualState> </VisualStateGroup> </VisualStateManager.VisualStateGroups> <!-- 给ContentPresenter命名,方便VisualState定位 --> <ContentPresenter x:Name="RowContentPresenter" Content="{TemplateBinding Content}" ContentTemplate="{TemplateBinding ContentTemplate}" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"/> </Border> </ControlTemplate> </Setter.Value> </Setter> </Style>
注意点
- 一定要给
ContentPresenter指定一个名字(比如示例里的RowContentPresenter),这样VisualState才能准确找到目标元素修改Foreground。 - 如果你之前尝试添加ContentControl出问题,大概率是没正确绑定
Content和ContentTemplate,或者没把它作为VisualState的目标元素。 - 别忘了处理
SelectedUnfocused状态,不然选中后失去焦点时字体颜色会变回默认。
内容的提问来源于stack exchange,提问作者renaldogg
相关产品推荐
相关产品推荐

