WPF中用戶(hù)控件和自定義控件
無(wú)論是在WPF中還是WinForm中,都有用戶(hù)控件(UserControl)和自定義控件(CustomControl),這兩種控件都是對(duì)已有控件的封裝,實(shí)現(xiàn)功能重用。但是兩者還是有一些區(qū)別,本文對(duì)這兩種控件進(jìn)行講解。
- 用戶(hù)控件
- 注重復(fù)合控件的使用,也就是多個(gè)現(xiàn)有控件組成一個(gè)可復(fù)用的控件組
- XAML和后臺(tái)代碼組成,綁定緊密
- 不支持模板重寫(xiě)
- 繼承自UserControl
- 自定義控件
- 完全自己實(shí)現(xiàn)一個(gè)控件,如繼承現(xiàn)有控件進(jìn)行功能擴(kuò)展,并添加新功能
- 后臺(tái)代碼和Generic.xaml進(jìn)行組合
- 在使用時(shí)支持模板重寫(xiě)
- 繼承自Control
用戶(hù)控件
用戶(hù)控件比較容易理解,與常見(jiàn)的WPF窗體類(lèi)似,值得注意一點(diǎn)的地方是內(nèi)部在使用綁定的時(shí)候,需要使用RelativeSource
的方式來(lái)綁定,以實(shí)現(xiàn)良好的封裝。一個(gè)簡(jiǎn)單的案例:
- 定義用戶(hù)控件
<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>
后臺(tái)代碼
//根據(jù)需要定義依賴(lài)屬性
//所需要綁定的值
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));
- 使用用戶(hù)控件
<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>
自定義控件
點(diǎn)擊添加自定義控件后,會(huì)增加一個(gè)CustomControl1.cs
文件以及一個(gè)Themes
目錄,在該目錄下有一個(gè)Generic.xaml
文件,該文件就是自定義控件的style。我們經(jīng)常針對(duì)某些控件進(jìn)行編輯模板
-創(chuàng)建副本
的操作而產(chǎn)生的style,其實(shí)就是Generic.xaml
中定義的style。另外,有時(shí)我們可能遇到一種情況,也就是相同的軟件在不同的Windows版本下運(yùn)行,表現(xiàn)形式可能會(huì)不同,甚至某些系統(tǒng)下運(yùn)行不了,這就是和不同系統(tǒng)下的默認(rèn)的Theme不同。其實(shí)wpf控件找不到自定義的樣式時(shí),會(huì)從系統(tǒng)獲取樣式,查找順序是,先查找所在的程序集,如果程序集定義了ThemeInfo
特性,那么會(huì)查看ThemeInfoDictionaryLocation
的屬性值,該屬性如果是None
則說(shuō)明沒(méi)有特定的主題資源,值為SourceAssembly
,說(shuō)明特定資源定義在程序集內(nèi)部,值為ExternalAssembly
則說(shuō)明在外部,如果還是沒(méi)有找到,則程序會(huì)在自身的themes/generic.xaml
中獲取,在generic.xaml
中獲取的其實(shí)就和系統(tǒng)默認(rèn)樣式相關(guān)。
不同xaml所對(duì)應(yīng)的系統(tǒng)主題
按鈕案例
C#文件
public class Switch : ToggleButton
{
static Switch()
{
//通過(guò)重寫(xiě)Metadata,控件就會(huì)通過(guò)程序集themes文件夾下的generic.xaml來(lái)尋找系統(tǒng)默認(rèn)樣式
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>
自定義控件中常用的知識(shí)點(diǎn)
- TemplatePart特性
在自定義控件中,有些控件是需要有名稱(chēng)的以便于調(diào)用,如在重寫(xiě)的OnApplyTemplate()方法中得到指定的button。這就要求用戶(hù)在使用控件時(shí),不能夠修改模板中的名稱(chēng)。
//應(yīng)用該控件時(shí)調(diào)用
public override void OnApplyTemplate()
{
UpButtonElement = GetTemplateChild("UpButton") as RepeatButton;
DownButtonElement = GetTemplateChild("DownButton") as RepeatButton;
}
所以在類(lèi)前面使用特性進(jìn)行標(biāo)注
[TemplatePart(Name = "UpButton", Type = typeof(RepeatButton))]
[TemplatePart(Name = "DownButton", Type = typeof(RepeatButton))]
public class Numeric : Control{}
- 視覺(jué)狀態(tài)的定義與調(diào)用
自定義控件中可以定義視覺(jué)狀態(tài)來(lái)呈現(xiàn)不同狀態(tài)下的效果。
在xml中定義視覺(jué)狀態(tài),不同組下的視覺(jué)狀態(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#中對(duì)應(yīng)視覺(jué)狀態(tài)的切換
private void UpdateStates(bool useTransitions)
{
if (IsFocused)
{
VisualStateManager.GoToState(this, "Focused", false);
}
else
{
VisualStateManager.GoToState(this, "Unfocused", false);
}
}
同時(shí)可以在后臺(tái)類(lèi)中使用特性來(lái)標(biāo)注
[TemplateVisualState(Name = "Focused", GroupName = "FocusedStates")]
[TemplateVisualState(Name = "Unfocused", GroupName = "FocusedStates")]
public class Numeric : Control{}
其實(shí)完全可以使用Trigger來(lái)實(shí)現(xiàn)該功能
案例學(xué)習(xí)源碼下載
分享幾個(gè)用戶(hù)控件和自定義控件的案例,效果如下:
文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-811071.html
源碼下載文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-811071.html
到了這里,關(guān)于WPF中用戶(hù)控件和自定義控件的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!