如何判断RichTextBox选中文字Foreground属性是否匹配指定StaticResource画刷
解决方案
要实现RichTextBox选中文字的Foreground属性切换,核心是正确获取选中文本的前景色状态并与目标静态资源画刷对比,以下是具体实现:
关键处理要点
- 提前获取静态资源画刷,避免重复查找提升性能
- 处理
DependencyProperty.UnsetValue情况:当选中区域内文本前景色不一致时,GetPropertyValue会返回该值,需针对性处理 - 直接通过引用对比判断画刷是否匹配(同一静态资源的实例引用一致)
修改后的完整代码
XAML(保持不变)
<Button Click="ToggleFontWeightAndForeground"/> <RichTextBox Name="RTEditor" Foreground="{StaticResource Brush.Brush01}"> ... </RichTextBox>
C#后台代码
private void ToggleFontWeightAndForeground(object sender, RoutedEventArgs e) { RichTextBox rtb = (parent.FindName("RTEditor") as RichTextBox); if (rtb != null && rtb.Selection != null) { // 预获取静态资源画刷,避免重复查找 var brush01 = (Brush)Application.Current.FindResource("Brush.Brush01"); var brush02 = (Brush)Application.Current.FindResource("Brush.Brush02"); // 切换FontWeight逻辑保持不变 var currentFontWeight = rtb.Selection.GetPropertyValue(Run.FontWeightProperty); if (currentFontWeight is FontWeight weight && weight == FontWeights.Normal) { rtb.Selection.ApplyPropertyValue(Run.FontWeightProperty, FontWeights.Bold); } else { rtb.Selection.ApplyPropertyValue(Run.FontWeightProperty, FontWeights.Normal); } // 切换Foreground颜色 var currentForeground = rtb.Selection.GetPropertyValue(Run.ForegroundProperty); // 判断当前选中文本的前景色状态 if (currentForeground == DependencyProperty.UnsetValue || !(currentForeground is Brush currentBrush) || currentBrush != brush01) { // 颜色不一致或当前不是brush01时,切换为brush01 rtb.Selection.ApplyPropertyValue(Run.ForegroundProperty, brush01); } else { // 当前是brush01时,切换为brush02 rtb.Selection.ApplyPropertyValue(Run.ForegroundProperty, brush02); } } }
细节说明
- 当选中文本包含多种不同前景色时,
GetPropertyValue返回DependencyProperty.UnsetValue,这里默认将其统一切换为Brush.Brush01,你可以根据需求调整这个逻辑 - 静态资源的Brush实例是单例引用,直接用
==比较即可判断是否为同一画刷,无需对比颜色值
内容的提问来源于stack exchange,提问作者AAng
相关产品推荐
相关产品推荐

