#1,178 – Custom Element Based on FrameworkElement

You can create custom user interface elements that derive from FrameworkElement.  Below is a simple example that renders itself as a graphical “X”.  We override the OnRender method (inherited from UIElement) and use the DrawingContext object to create visual content.

    public class MyElement : FrameworkElement
        protected override void OnRender(DrawingContext dc)
            dc.DrawLine(new Pen(Brushes.Blue, 2.0),
                new Point(0.0, 0.0),
                new Point(ActualWidth, ActualHeight));
            dc.DrawLine(new Pen(Brushes.Green, 2.0),
                new Point(ActualWidth, 0.0),
                new Point(0.0, ActualHeight));

Using the new element looks like this:


Here’s what it looks like at run-time:

If we host the Grid as a top-level element in a Window, our element is sized to fit the Grid, which sizes to fit the Window.  Because we render the element using ActualWidth and ActualHeight, it changes size as we resize the window.




#1,157 – Overridden Default Property Values Appear in Property Pane

In an earlier example of a custom control, we used the OverrideMetadata method to provide new default values for several dependency properties, as used in our control.  For example, we set the Stroke property to a green brush and StrokeThickness to 10.0.

        static CircularProgress()
            Brush myGreenBrush = new SolidColorBrush(Color.FromArgb(255, 6, 176, 37));

                new FrameworkPropertyMetadata(myGreenBrush));
                new FrameworkPropertyMetadata(Brushes.Transparent));

                new FrameworkPropertyMetadata(10.0));

These new values will show up as expected in the property pane within Visual Studio. Below, we can see both the green brush for Stroke and the value of 10.0 for StrokeThickness.


#1,135 – Alternatives to Creating a Custom Control

You’ll typically use existing WPF controls when creating an application’s user interface.  You can set property values for the control to customize both the look and behavior of the control.

If an existing control doesn’t provide the desired behavior or visual appearance, you can build a custom control.

Creating a custom control involves a fair amount of work.  Before deciding to create a new control, you should consider the alternatives listed below.

  • Use an existing control
    • Modify behavior or appearance using properties
    • Execute code in response to the control’s events
  • Use a control template to change the appearance of an existing control
  • Use a data template to change how bound data will be rendered by the control
  • Use triggers to change something in the control based on an event or changing data
  • Use value converter to customize data provided to the control
  • Use attached property to provide custom behavior