I have a UserControl and the default value for HorizontalContentAlignment
is HorizontalAlignment.Stretch
. In the constructor I set it to HorizontalAlignment.Left
.
When I use the UserControl and give it the property HorizontalAlignment.Right
in xaml, then that value is used, i.e. I cannot override the value in the constructor.
I could override the property in OnApplyTemplate
, OnRender
or the Loaded
event.
Is there any of these I should prefer?
Basically I want to avoid that someone can change the usercontrols HorizontalContentAlignment
.
Use the dependency property coercion callback (that is automatically called each time the value of a dependency property is about to change) to force the property to the desired value:
static YourUserControl () {
HorizontalContentAlignmentProperty.OverrideMetadata(
typeof(YourUserControl),
new FrameworkPropertyMetadata(
HorizontalAlignment.Stretch,
null,
CoerceHorizontalContentAlignment));
}
private static object CoerceHorizontalContentAlignment(DependencyObject d, object baseValue) {
return HorizontalAlignment.Stretch;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With