问题
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