.NET/WPF

WPF CustomControl

dozob 2021. 8. 15. 21:55

Choose the right base class

UIElement Layout, Input, Focus and Events
FrameworkElement Style, ToolTip, ContextMenu, and etc.
Control Template, Foreground, Background, FontSize
ContentControl ContentProperty
HeaderedContentControl HeaderProperty
TabControl, Expander, GroupBox
ItemsControl ItemCollection
Selector ComboBox, ListBox, ListView, TabControl
RangeBase Slider, ProgressBar
MinimumProperty, MaximumProperty

Override the Default Style

static MyCustomControl()
{
    DefaultStyleKeyProperty.OverrideMetadata(
        typeof(MyCustomControl),
        new FrameworkPropertyMetadata(typeof(MyCustomControl));
}

Create a default Style

<ResourceDictionary
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:sys="clr-namespace:System;assembly=mscorlib"
    xmlns:sd="clr-namespace:System.Drawing;assembly=System.Drawing"
    xmlns:swm="clr-namespace:System.Windows.Media;assembly=PresentationCore">
 
    <Style TargetType="{x:Type local:MyCustomControl}">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type local:MyCustomControl}">
                    ...
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
 
</ResourceDictionary>
public static readonly DependencyProperty MyContentProperty =
    DependencyProperty.Register(
        nameof(MyContent),
        typeof(object),
        typeof(MyCustomControl),
        new FrameworkPropertyMetadata(
            null,
            FrameworkPropertyMetadataOptions.AffectsRender |
            FrameworkPropertyMetadataOptions.AffectsParentMeasure));
 
public object MyContent
{
    get => GetValue(MyContentProperty);
    set => SetValue(MyContentProperty, value);
}