继承 UserControl 并连接到基本属性事件 [英] Inherit UserControl and hooking up to basic property events

查看:26
本文介绍了继承 UserControl 并连接到基本属性事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为 UWP 制作自定义 TextBox 以简化 Win2D 轮廓文本解决方案,为此我创建了一个 UserControl,其中仅包含一个画布,我将在其上绘制文本.

I'm making a custom TextBox for UWP to simplify Win2D outlined text solution, for that I created a UserControl that contains only a canvas on which I'll draw the text.

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

Of course I need some properties, like text, outline thickness and color, etc... I also need some properties that are already exposed by the inherited UserControl like Foreground, FontSize, FontFamily... So far so good, it seems like I won't need to implement each one of those common properties.

问题是当这些属性之一发生变化时,我无法找到一种方法来连接事件,因为我必须调用 Canvas.Invalidate() 方法来重绘它格式更改.

The problem is that I can't find a way to hook up an event when one of those properties changes, as I have to call the Canvas.Invalidate() method to redraw it when the format changes.

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

Looks like I have to hide all those properties and create new Dependency Properties to call Canvas.Invalidate(). There is no way to do it faster?

推荐答案

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

Nevermind, the answer was behind the corner.

在构造函数中,可以调用

In the constructor, you can call

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();
    }
}

这篇关于继承 UserControl 并连接到基本属性事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆