WPF自定義控件創建


WPF自定義控件創建

本文簡單的介紹一下WPF自定義控件的開發。

首先,我們打開VisualStudio創建一個WPF自定義控件庫,如下圖:

然后,我們可以看到創建的解決方案如下:

在解決方案中,我們看到了一個Themes文件夾和一個CS文件。

其中CS文件,就是我們需要編寫的自定義控件,里面的類繼承了Control類;而Themes則存放該控件的樣式。即,WPF自定義控件,是通過樣式給我們的編輯的控件類披上外衣而形成的。

下面,我們來編寫一個簡單的時間控件。

我們先將CustomControl1文件改名為KibaDateTime,然后打開KibaDateTime.cs文件,看到了一些控件應用提示,這些提示寫的是自定義控件的應用方式,我們先不看這些提示,因為他寫的不是很好理解。

接下來我們開始編寫時間控件,修改KibaDateTime類如下:

public class KibaDateTime : TextBox
    {
        private static Regex regex = new Regex("[0-9]+");
        #region 小時
        public static readonly DependencyProperty HourProperty = DependencyProperty.Register(
             "Hour", typeof(int), typeof(KibaDateTime), new FrameworkPropertyMetadata(00));
       
        public int Hour
        {
            get
            {
                return (int)GetValue(HourProperty);
            }
            set
            {
                SetValue(HourProperty, value);
            }
        } 
        #endregion
        #region 分鍾
        public static readonly DependencyProperty MinuteProperty = DependencyProperty.Register(
             "Minute", typeof(int), typeof(KibaDateTime), new FrameworkPropertyMetadata(00));
        
        public int Minute
        {
            get
            {
                return (int)GetValue(MinuteProperty);
            }
            set
            {
                SetValue(MinuteProperty, value);
            }
        }
        #endregion
        #region 秒
        public static readonly DependencyProperty SecondProperty = DependencyProperty.Register(
             "Second", typeof(int), typeof(KibaDateTime), new FrameworkPropertyMetadata(00)); 
        public int Second
        {
            get
            {
                return (int)GetValue(SecondProperty);
            }
            set
            {
                SetValue(SecondProperty, value);
            }
        }
        #endregion
        static KibaDateTime()
        {
            //當此依賴項屬性位於指定類型的實例上時為其指定替換元數據,以在該依賴項屬性繼承自基類型時重寫該屬性已存在的元數據。
            DefaultStyleKeyProperty.OverrideMetadata(typeof(KibaDateTime), new FrameworkPropertyMetadata(typeof(KibaDateTime))); 
        }
    }

如上述代碼所示,我們修改了KibaDateTime繼承的類;將Control改為了TextBox。

這樣,我們就可以在KibaDateTime控件的樣式中,用使用TextBox的屬性,進行綁定了。

然后,我們在控件類里定義三個依賴屬性,小時、分鍾、秒;之后,我們會把這個三個屬性,綁定到樣式中。

現在我們打開Theme文件下的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:KibaCustomControl">
    <Style TargetType="{x:Type local:KibaDateTime}">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type local:KibaDateTime}">
                    <Border Background="{TemplateBinding Background}"
                            BorderBrush="{TemplateBinding BorderBrush}"
                            BorderThickness="{TemplateBinding BorderThickness}">
                        
                    </Border>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style> 
</ResourceDictionary>

從代碼中可以看到,系統已經為我們定義好了KibaDateTime控件的外殼樣式。

我們需要做的就是將樣式內容添加進去。

我們在Border中,添加TextBox,然后進行小時、分鍾、秒的綁定,這里要用Binding來綁定。

添加的TextBox代碼如下,我們進行了一些簡單寬高和間距設置。

<TextBox Text="{Binding Hour,Mode=TwoWay,RelativeSource={RelativeSource TemplatedParent},UpdateSourceTrigger=PropertyChanged}" Width="24" Height="24" Padding="2,3,0,0" FontSize="12" ></TextBox>
<TextBox Text="{Binding Minute,Mode=TwoWay,RelativeSource={RelativeSource TemplatedParent},UpdateSourceTrigger=PropertyChanged}" Width="24" Height="24" Padding="2,3,0,0" FontSize="12" ></TextBox>
<TextBox Text="{Binding Second,Mode=TwoWay,RelativeSource={RelativeSource TemplatedParent},UpdateSourceTrigger=PropertyChanged}" Width="24" Height="24" Padding="2,3,0,0" FontSize="12" ></TextBox>

上述代碼使用了【RelativeSource={RelativeSource TemplatedParent}】來尋找綁定源,注意,這里一定要用TemplatedParent,不然無法綁定到我們控件類。

自定義控件到此為止,就已經定義好了。然后我們使用下剛剛定義好的控件。

WPF自定義控件應用

首先創建一個WPF項目,然后引用KibaCustomControl這個程序集。如下圖:

然后,在MainWindow.xaml頁面中,使用該控件。

修改MainWindow.xaml頁面代碼如下:

<Window x:Class="KibaTestControl.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:c="clr-namespace:KibaCustomControl;assembly=KibaCustomControl"
        xmlns:local="clr-namespace:KibaTestControl"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <DockPanel>
        <StackPanel VerticalAlignment="Top" Margin="10" Orientation="Horizontal">
            <c:KibaDateTime Name="dtHour"></c:KibaDateTime> 
            <Button Content="查看時間" Click="Button_Click" Width="75"/>
        </StackPanel>
    </DockPanel>
</Window>

其中【xmlns:c="clr-namespace:KibaCustomControl;assembly=KibaCustomControl"】這句話是將我們自定義的程序集內的控件,引入到當前頁。

【<c:KibaDateTime Text="00" ></c:KibaDateTime>】這句話就是我們自定義控件的應用了。

應用界面如下圖所示:

其中查看時間的事件代碼如下:

private void Button_Click(object sender, RoutedEventArgs e)
{
    MessageBox.Show("小時:"+dtHour.Hour+":"+dtHour.Minute + ":" + dtHour.Second);
}

修改時間,點擊查看時間,得到結果如下:

到此,這個簡單的WPF控件,就開發完了。

----------------------------------------------------------------------------------------------------

代碼已經傳到Github上了,歡迎大家下載。

Github地址:https://github.com/kiba518/KibaWpfCustomControl

----------------------------------------------------------------------------------------------------

注:此文章為原創,任何形式的轉載都請聯系作者獲得授權並注明出處!
若您覺得這篇文章還不錯,請點擊下方的推薦】,非常感謝!

 


免責聲明!

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



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