在WPF開發中,預設控制項的樣式常常無法滿足實際的應用需求,我們通常都會採用引入第三方控制項庫的方式來美化UI,使得應用軟體的設計風格更加統一。常用的WPF的UI控制項庫主要有以下幾種,如:Modern UI for WPF,MaterialDesignInXamlToolkit,PanuonUI,New ...
在WPF開發中,預設控制項的樣式常常無法滿足實際的應用需求,我們通常都會採用引入第三方控制項庫的方式來美化UI,使得應用軟體的設計風格更加統一。常用的WPF的UI控制項庫主要有以下幾種,如:Modern UI for WPF,MaterialDesignInXamlToolkit,PanuonUI,Newbeecoder.UI,WPF UI ,AduSkin,Panuon.UI.Silver,HandyControl,MahApps.Metro,Kino.Toolkit.Wpf,Xceed Extended WPF Toolkit™,Kino.Toolkit.Wpf,PP.Wpf,Adonis-ui,CC.WPFTools,CookPopularControl ,PropertyTools,RRQMSkin,Layui-WPF,Arthas-WPFUI,fruit-vent-design,Fluent.Ribbon,DMSkin WPF,EASkins_WPF,Rubyer-WPF,WPFDevelopers.Minimal ,WPFDevelopers,DevExpress WPF UI Library,ReactiveUI,Telerik UI for WPF等等,面對如此之多的WPF 第三方UI控制項庫,可謂各有特色,不一而同,對於具有選擇綜合症的開發人員來說,真的很難抉擇。在實際工作中,軟體經過統一的UI設計以後,和具體的業務緊密相連,往往這些通用的UI框架很難百分之百的契合,這時候,就需要我們自己去實現自定義控制項【Custom Control】來解決。本文以自定義視窗為例,簡述如何通過自定義控制項來擴展功能和樣式,僅供學習分享使用,如有不足之處,還請指正。
自定義控制項
自定義控制項Custom Control,通過集成現有控制項(如:Button , Window等)進行擴展,或者繼承Control基類兩種方式,和用戶控制項【User Control不太相同】,具體差異如下所示:
- 用戶控制項UserControl
- 註重覆合控制項的使用,也就是多個現有控制項組成一個可復用的控制項組
- XAML和後臺代碼組成,綁定緊密
- 不支持模板重寫
- 繼承自UserControl
- 自定義控制項CustomControl
- 完全自己實現一個控制項,如繼承現有控制項進行功能擴展,並添加新功能
- 後臺代碼和Generic.xaml進行組合
- 在使用時支持模板重寫
- 繼承自Control
本文所講解的側重點為自定義控制項,所以用戶控制項不再過多闡述。
WPF實現自定義控制項步驟
1. 創建控制項庫
首先在解決方案中,創建一個WPF類庫項目【SmallSixUI.Templates】,作為控制項庫,後續所有自定義控制項,都可以在此項目中開發。並創建Controls,Styles,Themes,Utils等文件夾,分別存放控制項類,樣式,主題,幫助類等內容,作為控制項庫的基礎結構,如下所示:
2. 創建自定義控制項
在Controls目錄中,創建自定義視窗AiWindow,繼承自Window類,即此類具有視窗的一切功能,並具有擴展出來的自定義功能。在此自定義視窗中,我們可以自定義視窗標題的字體顏色HeaderForeground,背景色HeaderBackground,是否顯示標題IsShowHeader,標題高度HeaderHeight,視窗動畫類型Type等內容,具體如下所示:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Automation.Text;
using System.Windows;
using SmallSixUI.Templates.Utils;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Shell;
namespace SmallSixUI.Templates.Controls
{
[TemplatePart(Name = "PART_CloseWindowButton", Type = typeof(Button))]
[TemplatePart(Name = "PART_MaxWindowButton", Type = typeof(Button))]
[TemplatePart(Name = "PART_MinWindowButton", Type = typeof(Button))]
public class AiWindow : Window
{
/// <summary>
/// 關閉窗體
/// </summary>
private Button PART_CloseWindowButton = null;
/// <summary>
/// 窗體縮放
/// </summary>
private Button PART_MaxWindowButton = null;
/// <summary>
/// 最小化窗體
/// </summary>
private Button PART_MinWindowButton = null;
/// <summary>
/// 設置重寫預設樣式
/// </summary>
static AiWindow()
{
StyleProperty.OverrideMetadata(typeof(AiWindow), new FrameworkPropertyMetadata(AiResourceHelper.GetStyle(nameof(AiWindow) + "Style")));
}
/// <summary>
/// 頂部內容
/// </summary>
[Bindable(true)]
public object HeaderContent
{
get { return (object)GetValue(HeaderContentProperty); }
set { SetValue(HeaderContentProperty, value); }
}
// Using a DependencyProperty as the backing store for HeaderContent. This enables animation, styling, binding, etc...
public static readonly DependencyProperty HeaderContentProperty =
DependencyProperty.Register("HeaderContent", typeof(object), typeof(AiWindow));
/// <summary>
/// 頭部標題欄文字顏色
/// </summary>
[Bindable(true)]
public Brush HeaderForeground
{
get { return (Brush)GetValue(HeaderForegroundProperty); }
set { SetValue(HeaderForegroundProperty, value); }
}
// Using a DependencyProperty as the backing store for HeaderForeground. This enables animation, styling, binding, etc...
public static readonly DependencyProperty HeaderForegroundProperty =
DependencyProperty.Register("HeaderForeground", typeof(Brush), typeof(AiWindow), new PropertyMetadata(Brushes.White));
/// <summary>
/// 頭部標題欄背景色
/// </summary>
[Bindable(true)]
public Brush HeaderBackground
{
get { return (Brush)GetValue(HeaderBackgroundProperty); }
set { SetValue(HeaderBackgroundProperty, value); }
}
// Using a DependencyProperty as the backing store for MyProperty. This enables animation, styling, binding, etc...
public static readonly DependencyProperty HeaderBackgroundProperty =
DependencyProperty.Register("HeaderBackground", typeof(Brush), typeof(AiWindow));
/// <summary>
/// 是否顯示頭部標題欄
/// </summary>
[Bindable(true)]
public bool IsShowHeader
{
get { return (bool)GetValue(IsShowHeaderProperty); }
set { SetValue(IsShowHeaderProperty, value); }
}
// Using a DependencyProperty as the backing store for IsShowHeader. This enables animation, styling, binding, etc...
public static readonly DependencyProperty IsShowHeaderProperty =
DependencyProperty.Register("IsShowHeader", typeof(bool), typeof(AiWindow), new PropertyMetadata(false));
/// <summary>
/// 動畫類型
/// </summary>
[Bindable(true)]
public AnimationType Type
{
get { return (AnimationType)GetValue(TypeProperty); }
set { SetValue(TypeProperty, value); }
}
// Using a DependencyProperty as the backing store for Type. This enables animation, styling, binding, etc...
public static readonly DependencyProperty TypeProperty =
DependencyProperty.Register("Type", typeof(AnimationType), typeof(AiWindow), new PropertyMetadata(AnimationType.Default));
/// <summary>
/// 頭部高度
/// </summary>
public int HeaderHeight
{
get { return (int)GetValue(HeaderHeightProperty); }
set { SetValue(HeaderHeightProperty, value); }
}
// Using a DependencyProperty as the backing store for HeaderHeight. This enables animation, styling, binding, etc...
public static readonly DependencyProperty HeaderHeightProperty =
DependencyProperty.Register("HeaderHeight", typeof(int), typeof(AiWindow), new PropertyMetadata(50));
public override void OnApplyTemplate()
{
base.OnApplyTemplate();
PART_CloseWindowButton = GetTemplateChild("PART_CloseWindowButton") as Button;
PART_MaxWindowButton = GetTemplateChild("PART_MaxWindowButton") as Button;
PART_MinWindowButton = GetTemplateChild("PART_MinWindowButton") as Button;
if (PART_MaxWindowButton != null && PART_MinWindowButton != null && PART_CloseWindowButton != null)
{
PART_MaxWindowButton.Click -= PART_MaxWindowButton_Click;
PART_MinWindowButton.Click -= PART_MinWindowButton_Click;
PART_CloseWindowButton.Click -= PART_CloseWindowButton_Click;
PART_MaxWindowButton.Click += PART_MaxWindowButton_Click;
PART_MinWindowButton.Click += PART_MinWindowButton_Click;
PART_CloseWindowButton.Click += PART_CloseWindowButton_Click;
}
}
private void PART_CloseWindowButton_Click(object sender, RoutedEventArgs e)
{
Close();
}
private void PART_MinWindowButton_Click(object sender, RoutedEventArgs e)
{
WindowState = WindowState.Minimized;
}
private void PART_MaxWindowButton_Click(object sender, RoutedEventArgs e)
{
if (WindowState == WindowState.Normal)
{
WindowState = WindowState.Maximized;
}
else
{
WindowState = WindowState.Normal;
}
}
protected override void OnSourceInitialized(EventArgs e)
{
base.OnSourceInitialized(e);
if (SizeToContent == SizeToContent.WidthAndHeight && WindowChrome.GetWindowChrome(this) != null)
{
InvalidateMeasure();
}
}
}
}
註意:在自定義控制項中,設置視窗標題的屬性要在樣式中進行綁定,所以需要定義為依賴屬性。在此控制項中用到的通用的類,則存放在Utils中。
3. 創建自定義控制項樣式
在Styles文件夾中,創建樣式資源文件【AiWindowStyle.xaml】,並將樣式的TargentType指定為Cotrols中創建的自定義類AiWindow。然後修改控制項的Template屬性,為其定義新的的ControlTemplate,來改變控制項的樣式。如下所示:
<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:Ai="clr-namespace:SmallSixUI.Templates.Controls">
<WindowChrome
x:Key="LayWindowChromeStyle"
CaptionHeight="56"
CornerRadius="0"
GlassFrameThickness="1"
NonClientFrameEdges="None"
ResizeBorderThickness="4"
UseAeroCaptionButtons="False" />
<Style x:Key="AiWindowStyle" TargetType="Ai:AiWindow">
<Setter Property="Background" Value="White" />
<Setter Property="HeaderBackground" Value="#23262E" />
<Setter Property="WindowChrome.WindowChrome">
<Setter.Value>
<WindowChrome
CaptionHeight="50"
CornerRadius="0"
GlassFrameThickness="1"
NonClientFrameEdges="None"
ResizeBorderThickness="4"
UseAeroCaptionButtons="False" />
</Setter.Value>
</Setter>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="Ai:AiWindow">
<Border
Height="{TemplateBinding HeaderHeight}"
Background="{TemplateBinding Background}"
BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}"
ClipToBounds="True">
<Border.Style>
<Style TargetType="Border">
<Style.Triggers>
<DataTrigger Binding="{Binding RelativeSource={RelativeSource AncestorType=Ai:AiWindow}, Path=WindowState}" Value="Maximized">
<Setter Property="Padding" Value="7" />
</DataTrigger>
</Style.Triggers>
</Style>
</Border.Style>
<Ai:AiTransition Style="{DynamicResource LayTransitionStyle}" Type="{TemplateBinding Type}">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="auto" />
<RowDefinition />
</Grid.RowDefinitions>
<Grid
x:Name="PART_Header"
Background="{TemplateBinding HeaderBackground}">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="auto" />
<ColumnDefinition Width="auto" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="auto" />
</Grid.ColumnDefinitions>
<Image
x:Name="Icon"
Width="32"
Height="32"
Margin="5"
Source="{TemplateBinding Icon}"
Stretch="Fill" />
<TextBlock
x:Name="HeaderText"
Grid.Column="1"
Margin="5,0"
FontSize="13"
VerticalAlignment="Center"
Foreground="{TemplateBinding HeaderForeground}"
Text="{TemplateBinding Title}" />
<ContentPresenter
Grid.Column="2"
ContentSource="HeaderContent"
WindowChrome.IsHitTestVisibleInChrome="true" />
<StackPanel Grid.Column="3" Orientation="Horizontal">
<StackPanel.Resources>
<ControlTemplate x:Key="WindowButtonTemplate" TargetType="Button">
<Grid x:Name="body" Background="Transparent">
<Border
Margin="3"
Background="Transparent"
WindowChrome.IsHitTestVisibleInChrome="True" />
<ContentPresenter HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}" />
</Grid>
<ControlTemplate.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter TargetName="body" Property="Background">
<Setter.Value>
<SolidColorBrush Opacity="0.1" Color="Black" />
</Setter.Value>
</Setter>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</StackPanel.Resources>
<Button
x:Name="PART_MinWindowButton"
Width="{Binding RelativeSource={RelativeSource Mode=Self}, Path=ActualHeight}"
Cursor="Hand"
Template="{DynamicResource WindowButtonTemplate}">
<Path
Width="15"
Height="2"
Data="M772.963422 533.491105l-528.06716 0c-12.38297 0-22.514491-10.131521-22.514491-22.514491l0 0c0-12.38297 10.131521-22.514491 22.514491-22.514491l528.06716 0c12.38297 0 22.514491 10.131521 22.514491 22.514491l0 0C795.477913 523.359584 785.346392 533.491105 772.963422 533.491105z"
Fill="{TemplateBinding HeaderForeground}"
IsHitTestVisible="false"
Stretch="Fill" />
</Button>
<Button
x:Name="PART_MaxWindowButton"
Width="{Binding RelativeSource={RelativeSource Mode=Self}, Path=ActualHeight}"
Cursor="Hand"
Template="{DynamicResource WindowButtonTemplate}">
<Path
x:Name="winCnangePath"
Width="15"
Height="15"
Data="M10.62,72a9.92,9.92,0,0,1-4-.86A11.15,11.15,0,0,1,.86,65.43,9.92,9.92,0,0,1,0,61.38V25A9.86,9.86,0,0,1,.86,21,11.32,11.32,0,0,1,3.18,17.6a11,11,0,0,1,3.38-2.32,9.68,9.68,0,0,1,4.06-.87H47a9.84,9.84,0,0,1,4.08.87A11,11,0,0,1,56.72,21,9.84,9.84,0,0,1,57.59,25V61.38a9.68,9.68,0,0,1-.87,4.06,11,11,0,0,1-2.32,3.38A11.32,11.32,0,0,1,51,71.14,9.86,9.86,0,0,1,47,72Zm36.17-7.21a3.39,3.39,0,0,0,1.39-.28,3.79,3.79,0,0,0,1.16-.77,3.47,3.47,0,0,0,1.07-2.53v-36a3.55,3.55,0,0,0-.28-1.41,3.51,3.51,0,0,0-.77-1.16,3.67,3.67,0,0,0-1.16-.77,3.55,3.55,0,0,0-1.41-.28h-36a3.45,3.45,0,0,0-1.39.28,3.59,3.59,0,0,0-1.14.79,3.79,3.79,0,0,0-.77,1.16,3.39,3.39,0,0,0-.28,1.39v36a3.45,3.45,0,0,0,.28,1.39A3.62,3.62,0,0,0,9.4,64.51a3.45,3.45,0,0,0,1.39.28Zm18-43.45a13.14,13.14,0,0,0-1.16-5.5,14.41,14.41,0,0,0-3.14-4.5,15,15,0,0,0-4.61-3,14.14,14.14,0,0,0-5.5-1.1H15A10.73,10.73,0,0,1,21.88.51,10.93,10.93,0,0,1,25.21,0H50.38a20.82,20.82,0,0,1,8.4,1.71A21.72,21.72,0,0,1,70.29,13.18,20.91,20.91,0,0,1,72,21.59v25.2a10.93,10.93,0,0,1-.51,3.33A10.71,10.71,0,0,1,70,53.05a10.84,10.84,0,0,1-2.28,2.36,10.66,10.66,0,0,1-3,1.58Z"
Fill="{TemplateBinding HeaderForeground}"
IsHitTestVisible="false"
Stretch="Fill" />
</Button>
<Button
x:Name="PART_CloseWindowButton"
Width="{Binding RelativeSource={RelativeSource Mode=Self}, Path=ActualHeight}"
Cursor="Hand"
Template="{DynamicResource WindowButtonTemplate}">
<Path
Width="15"
Height="15"
Data="M550.848 502.496l308.64-308.896a31.968 31.968 0 1 0-45.248-45.248l-308.608 308.896-308.64-308.928a31.968 31.968 0 1 0-45.248 45.248l308.64 308.896-308.64 308.896a31.968 31.968 0 1 0 45.248 45.248l308.64-308.896 308.608 308.896a31.968 31.968 0 1 0 45.248-45.248l-308.64-308.864z"
Fill="{TemplateBinding HeaderForeground}"
IsHitTestVisible="false"
Stretch="Fill" />
</Button>
</StackPanel>
</Grid>
<Grid Grid.Row="1" ClipToBounds="True">
<ContentPresenter />
</Grid>
</Grid>
</Ai:AiTransition>
</Border>
<ControlTemplate.Triggers>
<Trigger Property="WindowState" Value="Normal">
<Setter TargetName="winCnangePath" Property="Data" Value="M10.62,72a9.92,9.92,0,0,1-4-.86A11.15,11.15,0,0,1,.86,65.43,9.92,9.92,0,0,1,0,61.38V10.62a9.92,9.92,0,0,1,.86-4A11.15,11.15,0,0,1,6.57.86a9.92,9.92,0,0,1,4-.86H61.38a9.92,9.92,0,0,1,4.05.86,11.15,11.15,0,0,1,5.71,5.71,9.92,9.92,0,0,1,.86,4V61.38a9.92,9.92,0,0,1-.86,4.05,11.15,11.15,0,0,1-5.71,5.71,9.92,9.92,0,0,1-4.05.86Zm50.59-7.21a3.45,3.45,0,0,0,1.39-.28,3.62,3.62,0,0,0,1.91-1.91,3.45,3.45,0,0,0,.28-1.39V10.79a3.45,3.45,0,0,0-.28-1.39A3.62,3.62,0,0,0,62.6,7.49a3.45,3.45,0,0,0-1.39-.28H10.79a3.45,3.45,0,0,0-1.39.28A3.62,3.62,0,0,0,7.49,9.4a3.45,3.45,0,0,0-.28,1.39V61.21a3.45,3.45,0,0,0,.28,1.39A3.62,3.62,0,0,0,9.4,64.51a3.45,3.45,0,0,0,1.39.28Z" />
</Trigger>
<Trigger Property="IsShowHeader" Value="false">
<Setter TargetName="PART_Header" Property="Visibility" Value="Collapsed" />
</Trigger>
<Trigger Property="ResizeMode" Value="NoResize">
<Setter TargetName="PART_MaxWindowButton" Property="Visibility" Value="Collapsed" />
</Trigger>
<Trigger Property="Icon" Value="{x:Null}">
<Setter TargetName="Icon" Property="Visibility" Value="Collapsed" />
</Trigger>
<Trigger SourceName="HeaderText" Property="Text" Value="">
<Setter TargetName="HeaderText" Property="Visibility" Value="Collapsed" />
</Trigger>
<Trigger SourceName="HeaderText" Property="Text" Value="{x:Null}">
<Setter TargetName="HeaderText" Property="Visibility" Value="Collapsed" />
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ResourceDictionary>
4. 創建預設主題
在Themes文件夾中,創建主題資源文件【Generic.xaml】,併在主題資源文件中,引用上述創建的樣式資源,如下所示:
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="pack://application:,,,/SmallSixUI.Templates;component/Styles/AiWindowStyle.xaml"></ResourceDictionary>
<ResourceDictionary Source="pack://application:,,,/SmallSixUI.Templates;component/Styles/AiTransitionStyle.xaml"></ResourceDictionary>
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
主題:主題資源文件,是為了整合一組資源樣式,來形成一套主題。同一主題之內,風格統一;不同主題之間相互獨立,風格迥異。
應用自定義控制項庫
1. 創建應用程式
在解決方案中,創建WPF應用程式【SmallSixUI.App】,並引用控制項庫【SmallSixUI.Templates】,如下所示:
2. 引入主題資源
在應用程式的啟動類App.xaml中,引入主題資源文件,如下所示:
<Application x:Class="SmallSixUI.App.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:SmallSixUI.App"
StartupUri="MainWindow.xaml">
<Application.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="pack://application:,,,/SmallSixUI.Templates;component/Themes/Generic.xaml"></ResourceDictionary>
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Application.Resources>
</Application>
3. 創建測試視窗
在應用程式中,創建測試視窗【SmallSixWindow.xaml】,添加控制項庫命名控制項【Ai】,並修改視窗的繼承類為【AiWindow】,然後設置視窗的背景色,logo,標題等,如下所示:
SmallSixWindow.xaml文件中,如下所示:
<Ai:AiWindow x:Class="SmallSixUI.App.SmallSixWindow"
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:Ai="clr-namespace:SmallSixUI.Templates.Controls;assembly=SmallSixUI.Templates"
xmlns:local="clr-namespace:SmallSixUI.App"
mc:Ignorable="d"
IsShowHeader="True"
HeaderBackground="#446180"
HeaderHeight="80"
Icon="logo.png"
Title="小六公子的UI設計視窗" Height="450" Width="800">
<Grid>
</Grid>
</Ai:AiWindow>
SmallSixWindow.xaml.cs中修改繼承類,如下所示:
using SmallSixUI.Templates.Controls;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
namespace SmallSixUI.App
{
/// <summary>
/// XWindow.xaml 的交互邏輯
/// </summary>
public partial class SmallSixWindow : AiWindow
{
public SmallSixWindow()
{
InitializeComponent();
}
}
}
運行程式
通過Visual Studio運行程式,如下所示:
普通預設視窗,如下所示:
自定義視窗
應用自定義樣式的視窗,如下所示:
以上就是WPF自定義控制項庫之視窗的全部內容。希望可以拋磚引玉,一起學習,共同進步。
作者:小六公子
出處:http://www.cnblogs.com/hsiang/
本文版權歸作者和博客園共有,寫文不易,支持原創,歡迎轉載【點贊】,轉載請保留此段聲明,且在文章頁面明顯位置給出原文連接,謝謝。
關註個人公眾號,定時同步更新技術及職場文章