【发布时间】:2016-03-12 00:46:31
【问题描述】:
我正在尝试扩展 Label 控件以支持抚摸文本(有点像 this 问题的答案,但我想扩展 Label 来做到这一点,而不是编写一个全新的(ish)控件)。
我已经取得了一定的成功,但我碰壁了,我无法找到标签如何呈现文本。如果我能弄清楚这是怎么发生的(并覆盖它),那么我可以在我的扩展 Label 类中添加一些属性(一个画笔和一个双精度)并设置好。
这是我目前所拥有的:
public class StrokedLabel : Label {
public static readonly DependencyProperty
StrokeProperty = DependencyProperty.Register(
"Stroke",
typeof( Brush ),
typeof( StrokedLabel ),
new PropertyMetadata(
Brushes.Red,
( S, E ) => ( S as StrokedLabel ).InvalidateVisual( ) ) ),
StrokeWidthProperty = DependencyProperty.Register(
"StrokeWidth",
typeof( double ),
typeof( StrokedLabel ),
new PropertyMetadata(
2.0D,
( S, E ) => ( S as StrokedLabel ).InvalidateVisual( ) ) );
/// <summary>
/// Get or Set Stroke Brush.
/// </summary>
public Brush Stroke {
get { return this.GetValue( StrokeProperty ) as Brush; }
set { this.SetValue( StrokeProperty, value ); }
}
/// <summary>
/// Get or Set Stroke Width
/// </summary>
public double StrokeWidth {
get { return ( double )this.GetValue( StrokeWidthProperty ); }
set { this.SetValue( StrokeWidthProperty, value ); }
}
protected override void OnRender( DrawingContext drawingContext ) {
if ( !( this.Content is string ) )
base.OnRender( drawingContext );
else {
drawingContext.DrawGeometry(
this.Foreground,
new Pen(
this.Stroke,
this.StrokeWidth ),
new FormattedText(
this.Content.ToString( ),
CultureInfo.CurrentUICulture,
this.FlowDirection,
new Typeface(
this.FontFamily,
this.FontStyle,
this.FontWeight,
this.FontStretch ),
this.FontSize,
this.Foreground ).BuildGeometry( new Point( 0.0D, 0.0D ) ) );
}
}
}
我已经尝试跟踪继承链,并且我已经做到了 UIElement,它定义了 OnRender 方法,但我找不到在继承链中实际使用该方法的位置(或者如果它甚至涉及)。
我觉得文本是在 ContentControl 中呈现的(Label 直接从该控件继承),但我找不到在该控件中呈现文本的位置。是在 Content Control 中渲染,还是在 Content Control 继承的(Control 类)中渲染?
在哪个类中(以及通过哪个方法)呈现为文本的字符串?
【问题讨论】:
-
已经很久了,我现在无法对其进行测试,但是:我认为它是通过内容控制功能完成的,该功能试图通过其默认模板选择器 (can be overridden) 解析内容模板。如果选择器找到
string,它会返回一个包含TextBlock的模板。我认为您可以通过Application.Resources设置TextBlock的样式,这适用于模板边界。 -
等等,很明显,这是一个
AccessText,因为您希望字符串中所述键前面的“_”给出的访问键的下划线。
标签: c# wpf inheritance text label