4

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.

1 Answer 1

5

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; } 
Sign up to request clarification or add additional context in comments.

2 Comments

I accept it, the Coerce is a correct word to use. However it is somewhat more code then e.g. adding it to OnApplyTemplate. Any reason to prefer coerce above the latter?
The coerce callback is called whenever the property value changes. You don't have to clutter your code with calls to override the user value everywhere it's possible or for every mean (remember a property can be changed through a binding or animation): that's an universal solution. Plus, coercing means that the user will always see the actual coerced value (Stretch) of the property. Additionally, coercing won't overwrite any binding that may have been set on the property, and the user-specified value is stored for future use if needed.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.