Lessons in this course (9)

8. WinForms and WPF custom controls

IntermediateMediumLesson 8 of 9

WinForms:

ApproachHow
UserControlCombine existing controls in the designer (address panel)
Inherited controlclass NumericTextBox : TextBox — override OnKeyPress to allow digits only
Owner-drawn / custom-drawnclass Gauge : Control — override OnPaint(PaintEventArgs e) and draw with GDI+, call Invalidate() when data changes
csharp
public class NumericTextBox : TextBox
{
    protected override void OnKeyPress(KeyPressEventArgs e)
    {
        if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar)) e.Handled = true;   // block non-digits
        base.OnKeyPress(e);
    }
}

WPF: UserControl (XAML composition) vs custom control (Control subclass with a default ControlTemplate in Themes/Generic.xaml, fully re-stylable); expose data through dependency properties (support binding, styling, animation) and routed events.

csharp
public class RatingControl : Control
{
    public static readonly DependencyProperty ValueProperty =
        DependencyProperty.Register(nameof(Value), typeof(int), typeof(RatingControl), new FrameworkPropertyMetadata(0, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault));
    public int Value { get => (int)GetValue(ValueProperty); set => SetValue(ValueProperty, value); }
    static RatingControl() => DefaultStyleKeyProperty.OverrideMetadata(typeof(RatingControl), new FrameworkPropertyMetadata(typeof(RatingControl)));
}