WPF 自定義控件 ---- 繼承自Control 類


WPF自動定義控件一般有三種方式:

第一種是建立一個UserControl,這是最簡單的方式,也是比較常用的方式。在這種方式中,可以直接使用VS的設計器進行UI的設計,並且可以直接添加事件處理函數,還可以為它設計對應的ViewMode。與一般的Window的設計沒什么區別。

第二種是繼承自Control類,這也是一種比較常用的方式。這種方式需要提供一個默認的ControlTemplate,並且使用該控件的開發者,可以為該控件提供新的ControlTemplate和DataTemplate。

第三種是繼承自FrameWorkElement,這種方式是比較底層的設計新的UserControl的方法。需要重寫Render方法類渲染UserControl。在之后的隨筆中會添加,本隨筆針對第二種情況。

 

1. 在Themes---> Generic.xaml文件中提供默認的ControlTemplate,文件夾名Themes和Generic.xaml是固定的,不可更改。

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                    xmlns:local="clr-namespace:TimeLine">
    <Style TargetType="{x:Type local:TimeLineControl}">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type local:TimeLineControl}">
                    <StackPanel Orientation="Horizontal">
                        <TextBlock x:Name="PART_DateTimeTextBox" Text="{TemplateBinding DateTimeMsg}"/>
                        <TextBlock x:Name="PART_ContentTextBox" Text="{TemplateBinding ContentMsg}"/>
                    </StackPanel>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
</ResourceDictionary>
2. 提供后台的邏輯代碼
namespace TimeLine
{
    [TemplatePart(Name = TimeLineControl.ElementDateTimeTextBox, Type = typeof(TextBlock))]
    [TemplatePart(Name = TimeLineControl.ElementContentTextBox, Type = typeof(TextBlock))]
    public class TimeLineControl : Control
    {
        private const string ElementDateTimeTextBox = "PART_DateTimeTextBox";
        private const string ElementContentTextBox = "PART_ContentTextBox";
        TextBlock dateTimeTB = null;
        TextBlock contentMsgTB = null;
 
        public TimeLineControl()
        {
            DefaultStyleKeyProperty.OverrideMetadata(typeof(TimeLineControl), new FrameworkPropertyMetadata(typeof(TimeLineControl)));
            ContentMsg = "Hello World";
            DateTimeMsg = "DateTime";
        }
 
        public override void OnApplyTemplate()
        {
            base.OnApplyTemplate();
 
            dateTimeTB = GetTemplateChild(ElementDateTimeTextBox) as TextBlock;
            contentMsgTB = GetTemplateChild(ElementContentTextBox) as TextBlock;
        }
 
        /// <summary>
        /// Registers a dependency property as backing store for the Content property
        /// </summary>
        public static readonly DependencyProperty ContentMsgProperty =
            DependencyProperty.Register("ContentMsg"typeof(object), typeof(TimeLineControl),
            new FrameworkPropertyMetadata(null,
                  FrameworkPropertyMetadataOptions.AffectsRender |
                  FrameworkPropertyMetadataOptions.AffectsParentMeasure));
 
        /// <summary>
        /// Gets or sets the Content.
        /// </summary>
        /// <value>The Content.</value>
        public object ContentMsg
        {
            get { return (object)GetValue(ContentMsgProperty); }
            set { SetValue(ContentMsgProperty, value); }
        }
 
        public static readonly DependencyProperty DateTimeMsgProperty =
            DependencyProperty.Register("DateTimeMsg"typeof(object), typeof(TimeLineControl),
            new FrameworkPropertyMetadata(null,
                  FrameworkPropertyMetadataOptions.AffectsRender |
                  FrameworkPropertyMetadataOptions.AffectsParentMeasure));
        public object DateTimeMsg
        {
            get
            {
                return (object)GetValue(DateTimeMsgProperty);
            }
            set
            {
                SetValue(DateTimeMsgProperty, value);
            }
        }
    }
}


自定義控件時,常用的基類有:
  • UIElement - The most lightweight base class to start from. It has support for LIFE - Layout, Input, Focus and Events.
  • FrameworkElement - Derives from UIElement and adds support for styling, tooltips and context menus. It is first base class that takes part in the logical tree and so it supports data binding and resource lookup.
  • Control - is the most common base class for controls (its name speaks for itself). It supports templates and adds some basic properties as ForegroundBackground or FontSize.
  • ContentControl - is a control that has an additional Content property. This is often used for simple containers.
  • HeaderedContentControl - is a control that has an Content and a Header property. This is used for controls with a header like Expander, TabControl, GroupBox,...
  • ItemsControl - a control that has an additional Items collection. This is a good choice for controls that display a dynamic list of items without selection.
  • Selector - an ItemsControl whose items can be indexed and selected. This is used for ListBox, ComboBox, ListView, TabControl...
  • RangeBase - is the base class for controls that display a value range like Sliders or ProgressBars. It adds an Value,Minimum and Maximum property.


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM