继承 UserControl 并连接到基本 属性 事件

Inherit UserControl and hooking up to basic property events

我正在为 UWP 制作自定义文本框以简化 Win2D 概述文本解决方案,为此我创建了一个仅包含 canvas 我将在其上绘制文本的 UserControl。

当然我需要一些属性,比如文本、轮廓粗细和颜色等等... 我还需要一些已经由继承的 UserControl 公开的属性,如 Foreground、FontSize、FontFamily ... 到目前为止一切顺利,看来我不需要实现这些通用属性中的每一个。

问题是当其中一个属性发生变化时,我找不到连接事件的方法,因为当格式发生变化时我必须调用 Canvas.Invalidate() 方法来重绘它。

看来我必须隐藏所有这些属性并创建新的依赖属性才能调用 Canvas.Invalidate()。 有没有办法做得更快?

没关系,答案就在角落里。

在构造函数中,可以调用

RegisterPropertyChangedCallback(DependencyProperty dp, DependencyPropertyChangedCallback callback);

例如:

public OutlinedText()
{
    InitializeComponent();

    RegisterPropertyChangedCallback(FontFamilyProperty, OnPropertyChanged);
        RegisterPropertyChangedCallback(FontSizeProperty, OnPropertyChanged);
}

private void OnPropertyChanged(DependencyObject sender, DependencyProperty dp)
{
    OutlinedText instance = sender as OutlinedText;
    if (instance != null)
    {
        //Caching the value into CanvasTextFormat for faster drawn execution
        if (dp == FontFamilyProperty)
            instance.TextFormat.FontFamily = instance.FontFamily.Source;
        else if (dp == FontSizeProperty)
            instance.TextFormat.FontSize = (Single)instance.FontSize;

        instance.needsResourceRecreation = true;
        instance.canvas.Invalidate();
    }
}