Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Override DependencyProperty in a UserControl

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.

like image 312
Gerard Avatar asked Mar 12 '14 16:03

Gerard


1 Answers

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;
}   
like image 76
Julien Lebosquain Avatar answered Oct 29 '22 16:10

Julien Lebosquain