Inherit UserControl and hooking up to basic property events

有些话、适合烂在心里 提交于 2019-12-23 05:40:57

问题


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.

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.

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.

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?


回答1:


Nevermind, the answer was behind the corner.

In the constructor, you can call

RegisterPropertyChangedCallback(DependencyProperty dp, DependencyPropertyChangedCallback callback);

For example:

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


来源:https://stackoverflow.com/questions/41824741/inherit-usercontrol-and-hooking-up-to-basic-property-events

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!