Search code examples
c#wpf

WPF Control ignores HorizontalAlignment=Stretch if WidthProperty Metadata is overridden


When I try to override the metadata of WidthProperty, the control will ignore HorizontalAlignment=Stretch. I only want my custom control to have a default value for its width.

Code:

WidthProperty.OverrideMetadata(typeof(Switch), new FrameworkPropertyMetadata(100.0, FrameworkPropertyMetadataOptions.AffectsMeasure | FrameworkPropertyMetadataOptions.AffectsArrange | FrameworkPropertyMetadataOptions.Inherits));

This is how it looks if overridden: Control not stretched

Without override: enter image description here

So how do I properly override the metadata of WidthProperty? The same also goes for HeightProperty. I already tried CoerceValueCallbacks but it failed.


Solution

  • Setting the metadata of Width in the control is not the way to go, the control shouldn't be concerned with presentation. For this you would use Styles.

    You probably set the default in the metadata because of the low precendence, but that is only useful if you set the Width somewhere else, in this case HorizontalAligment is some other property that has nothing to do with the Width's default.

    I guess you might want to set the MinWidth in the style.