詳解WPF中用戶控件和自定義控件的使用
介紹
無論是在WPF中還是WinForm中,都有用戶控件(UserControl)和自定義控件(CustomControl),這兩種控件都是對已有控件的封裝,實現(xiàn)功能重用。但是兩者還是有一些區(qū)別,本文對這兩種控件進行講解。
1.用戶控件
- 注重復合控件的使用,也就是多個現(xiàn)有控件組成一個可復用的控件組
- XAML和后臺代碼組成,綁定緊密
- 不支持模板重寫
- 繼承自UserControl
2.自定義控件
- 完全自己實現(xiàn)一個控件,如繼承現(xiàn)有控件進行功能擴展,并添加新功能
- 后臺代碼和Generic.xaml進行組合
- 在使用時支持模板重寫
- 繼承自Control
用戶控件
用戶控件比較容易理解,與常見的WPF窗體類似,值得注意一點的地方是內部在使用綁定的時候,需要使用RelativeSource
的方式來綁定,以實現(xiàn)良好的封裝。一個簡單的案例:
定義用戶控件
<UserControl x:Class="WpfApp19.UserControl1" 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:local="clr-namespace:WpfApp19" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" d:DesignHeight="450" d:DesignWidth="800" mc:Ignorable="d"> <Grid> <!--下面綁定都要用RelativeSource作為源--> <StackPanel> <TextBox Width="100" BorderThickness="2" Text="{Binding value, RelativeSource={RelativeSource AncestorType=UserControl}}" /> <Button Width="100" Command="{Binding Command, RelativeSource={RelativeSource AncestorType=UserControl}}" Content="Ok" /> </StackPanel> </Grid> </UserControl>
后臺代碼
//根據(jù)需要定義依賴屬性 //所需要綁定的值 public int value { get { return (int)GetValue(valueProperty); } set { SetValue(valueProperty, value); } } public static readonly DependencyProperty valueProperty = DependencyProperty.Register("value", typeof(int), typeof(UserControl1), new PropertyMetadata(0)); //所需要綁定的命令 public ICommand Command { get { return (ICommand)GetValue(CommandProperty); } set { SetValue(CommandProperty, value); } } public static readonly DependencyProperty CommandProperty = DependencyProperty.Register("Command", typeof(ICommand), typeof(UserControl1), new PropertyMetadata(default(ICommand))); //所需要綁定的命令參數(shù) public object CommandParemeter { get { return (object)GetValue(CommandParemeterProperty); } set { SetValue(CommandParemeterProperty, value); } } public static readonly DependencyProperty CommandParemeterProperty = DependencyProperty.Register("CommandParemeter", typeof(object), typeof(UserControl1), new PropertyMetadata(0));
使用用戶控件
<Window x:Class="WpfApp19.MainWindow" ... xmlns:local="clr-namespace:WpfApp19" Title="MainWindow" Height="450" Width="800"> <Grid> <local:UserControl1 value="{Binding }" Command="{Binding }"/> </Grid> </Window>
自定義控件
點擊添加自定義控件后,會增加一個CustomControl1.cs
文件以及一個Themes
目錄,在該目錄下有一個Generic.xaml
文件,該文件就是自定義控件的style。我們經(jīng)常針對某些控件進行編輯模板-創(chuàng)建副本的操作而產生的style,其實就是Generic.xaml中定義的style。另外,有時我們可能遇到一種情況,也就是相同的軟件在不同的Windows版本下運行,表現(xiàn)形式可能會不同,甚至某些系統(tǒng)下運行不了,這就是和不同系統(tǒng)下的默認的Theme不同。其實wpf控件找不到自定義的樣式時,會從系統(tǒng)獲取樣式,查找順序是,先查找所在的程序集,如果程序集定義了ThemeInfo
特性,那么會查看ThemeInfoDictionaryLocation
的屬性值,該屬性如果是None
則說明沒有特定的主題資源,值為SourceAssembly
,說明特定資源定義在程序集內部,值為ExternalAssembly
則說明在外部,如果還是沒有找到,則程序會在自身的themes/generic.xaml
中獲取,在generic.xaml
中獲取的其實就和系統(tǒng)默認樣式相關。
不同xaml所對應的系統(tǒng)主題
按鈕案例
C#文件
public class Switch : ToggleButton { static Switch() { //通過重寫Metadata,控件就會通過程序集themes文件夾下的generic.xaml來尋找系統(tǒng)默認樣式 DefaultStyleKeyProperty.OverrideMetadata(typeof(Switch), new FrameworkPropertyMetadata(typeof(Switch))); } }
Themes文件夾下的Generic.xaml文件
注意在該文件中不能有中文,注釋也不行
<Style TargetType="{x:Type local:Switch}"> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="{x:Type local:Switch}"> <Grid> <Border Name="dropdown" Width="{Binding RelativeSource={RelativeSource Self}, Path=ActualHeight}" Margin="-23" CornerRadius="{Binding RelativeSource={RelativeSource Self}, Path=ActualHeight}" Visibility="Collapsed"> <Border.Background> <RadialGradientBrush> <GradientStop Offset="1" Color="Transparent" /> <GradientStop Offset="0.7" Color="#5500D787" /> <GradientStop Offset="0.59" Color="Transparent" /> </RadialGradientBrush> </Border.Background> </Border> <Border Name="bor" Width="{Binding RelativeSource={RelativeSource Self}, Path=ActualHeight}" Background="Gray" BorderBrush="DarkGreen" BorderThickness="5" CornerRadius="{Binding RelativeSource={RelativeSource Self}, Path=ActualHeight}"> <Border Name="bor1" Width="{Binding RelativeSource={RelativeSource Self}, Path=ActualHeight}" Margin="2" Background="#FF00C88C" CornerRadius="{Binding RelativeSource={RelativeSource Self}, Path=ActualHeight}" /> </Border> </Grid> <ControlTemplate.Triggers> <Trigger Property="IsChecked" Value="True"> <Trigger.EnterActions> <BeginStoryboard> <Storyboard> <ColorAnimation Storyboard.TargetName="bor1" Storyboard.TargetProperty="Background.Color" To="White" Duration="0:0:0.5" /> <ColorAnimation Storyboard.TargetName="bor" Storyboard.TargetProperty="BorderBrush.Color" To="#FF32FAC8" Duration="0:0:0.5" /> <ObjectAnimationUsingKeyFrames Storyboard.TargetName="dropdown" Storyboard.TargetProperty="Visibil <DiscreteObjectKeyFrame KeyTime="0:0:0.3"> <DiscreteObjectKeyFrame.Value> <Visibility>Visible</Visibility> </DiscreteObjectKeyFrame.Value> </DiscreteObjectKeyFrame> </ObjectAnimationUsingKeyFrames> </Storyboard> </BeginStoryboard> </Trigger.EnterActions> <Trigger.ExitActions> <BeginStoryboard> <Storyboard> <ColorAnimation Storyboard.TargetName="bor1" Storyboard.TargetProperty="Background.Color" /> <ColorAnimation Storyboard.TargetName="bor" Storyboard.TargetProperty="BorderBrush.Color" /> <ObjectAnimationUsingKeyFrames Storyboard.TargetName="dropdown" Storyboard.TargetProperty="Visibil <DiscreteObjectKeyFrame KeyTime="0:0:0.3"> <DiscreteObjectKeyFrame.Value> <Visibility>Collapsed</Visibility> </DiscreteObjectKeyFrame.Value> </DiscreteObjectKeyFrame> </ObjectAnimationUsingKeyFrames> </Storyboard> </BeginStoryboard> </Trigger.ExitActions> </Trigger> </ControlTemplate.Triggers> </ControlTemplate> </Setter.Value> </Setter> </Style>
使用自定控件
<Grid> <local:Switch Width="100" Height="100" /> </Grid>
自定義控件中常用的知識點
TemplatePart特性
在自定義控件中,有些控件是需要有名稱的以便于調用,如在重寫的OnApplyTemplate()方法中得到指定的button。這就要求用戶在使用控件時,不能夠修改模板中的名稱。
//應用該控件時調用 public override void OnApplyTemplate() { UpButtonElement = GetTemplateChild("UpButton") as RepeatButton; DownButtonElement = GetTemplateChild("DownButton") as RepeatButton; }
所以在類前面使用特性進行標注
[TemplatePart(Name = "UpButton", Type = typeof(RepeatButton))] [TemplatePart(Name = "DownButton", Type = typeof(RepeatButton))] public class Numeric : Control{}
視覺狀態(tài)的定義與調用
自定義控件中可以定義視覺狀態(tài)來呈現(xiàn)不同狀態(tài)下的效果。
在xml中定義視覺狀態(tài),不同組下的視覺狀態(tài)是互斥的
<VisualStateManager.VisualStateGroups> <VisualStateGroup Name="FocusStates"> <VisualState Name="Focused"> <Storyboard> <ObjectAnimationUsingKeyFrames Storyboard.TargetName="FocusVisual" Storyboard.TargetProperty="Visibility" Duration="0"> <DiscreteObjectKeyFrame KeyTime="0"> <DiscreteObjectKeyFrame.Value> <Visibility>Visible</Visibility> </DiscreteObjectKeyFrame.Value> </DiscreteObjectKeyFrame> </ObjectAnimationUsingKeyFrames> </Storyboard> </VisualState> <VisualState Name="Unfocused"/> </VisualStateGroup> </VisualStateManager.VisualStateGroups>
在C#中對應視覺狀態(tài)的切換
private void UpdateStates(bool useTransitions) { if (IsFocused) { VisualStateManager.GoToState(this, "Focused", false); } else { VisualStateManager.GoToState(this, "Unfocused", false); } }
同時可以在后臺類中使用特性來標注
[TemplateVisualState(Name = "Focused", GroupName = "FocusedStates")] [TemplateVisualState(Name = "Unfocused", GroupName = "FocusedStates")] public class Numeric : Control{}
其實完全可以使用Trigger來實現(xiàn)該功能
以上就是詳解WPF中用戶控件和自定義控件的使用的詳細內容,更多關于WPF用戶控件 自定義控件的資料請關注腳本之家其它相關文章!
相關文章
C# wpf Canvas中實現(xiàn)控件拖動調整大小的示例
本文主要介紹了C# wpf Canvas中實現(xiàn)控件拖動調整大小的示例,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2022-08-08C#實現(xiàn)將DataTable內容輸出到Excel表格的方法
這篇文章主要介紹了C#實現(xiàn)將DataTable內容輸出到Excel表格的方法,較為詳細的分析了C#基于DataTable保存Excel數(shù)據(jù)的相關技巧,具有一定參考借鑒價值,需要的朋友可以參考下2015-08-08