#1,154 – Providing Default Values for Standard Dependency Properties in Custom Controls
September 9, 2014 1 Comment
When you define a custom control, you may define some custom dependency properties. For each property that you define, you specify metadata for your new dependency property, including default values.
You may also want to specify default values for dependency properties used by your class, but defined elsewhere. In the code fragment below, we’re defining a custom shape that inherits from the Shape class. We don’t want the user to have to provide values for the Stroke and Fill properties, so we use the OverrideMetadata method to provide default values. Note that the user can still provide their own values for these properties.
public class PieSlice : Shape { static PieSlice() { Brush myGreenBrush = new SolidColorBrush(Color.FromArgb(255, 6, 176, 37)); myGreenBrush.Freeze(); StrokeProperty.OverrideMetadata( typeof(PieSlice), new FrameworkPropertyMetadata(myGreenBrush)); FillProperty.OverrideMetadata( typeof(PieSlice), new FrameworkPropertyMetadata(myGreenBrush)); } // Remainder of custom control here.. }