最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

詳解WPF中用戶控件和自定義控件的使用

 更新時間:2023年03月02日 11:31:28   作者:步、步、為營  
無論是在WPF中還是WinForm中,都有用戶控件(UserControl)和自定義控件(CustomControl),這兩種控件都是對已有控件的封裝,實(shí)現(xiàn)功能重用。但是兩者還是有一些區(qū)別,本文對這兩種控件進(jìn)行講解

介紹

無論是在WPF中還是WinForm中,都有用戶控件(UserControl)和自定義控件(CustomControl),這兩種控件都是對已有控件的封裝,實(shí)現(xiàn)功能重用。但是兩者還是有一些區(qū)別,本文對這兩種控件進(jìn)行講解。

1.用戶控件

  • 注重復(fù)合控件的使用,也就是多個現(xiàn)有控件組成一個可復(fù)用的控件組
  • XAML和后臺代碼組成,綁定緊密
  • 不支持模板重寫
  • 繼承自UserControl

2.自定義控件

  • 完全自己實(shí)現(xiàn)一個控件,如繼承現(xiàn)有控件進(jìn)行功能擴(kuò)展,并添加新功能
  • 后臺代碼和Generic.xaml進(jìn)行組合
  • 在使用時支持模板重寫
  • 繼承自Control

用戶控件

用戶控件比較容易理解,與常見的WPF窗體類似,值得注意一點(diǎn)的地方是內(nèi)部在使用綁定的時候,需要使用RelativeSource的方式來綁定,以實(shí)現(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>

自定義控件

點(diǎn)擊添加自定義控件后,會增加一個CustomControl1.cs文件以及一個Themes目錄,在該目錄下有一個Generic.xaml文件,該文件就是自定義控件的style。我們經(jīng)常針對某些控件進(jìn)行編輯模板-創(chuàng)建副本的操作而產(chǎn)生的style,其實(shí)就是Generic.xaml中定義的style。另外,有時我們可能遇到一種情況,也就是相同的軟件在不同的Windows版本下運(yùn)行,表現(xiàn)形式可能會不同,甚至某些系統(tǒng)下運(yùn)行不了,這就是和不同系統(tǒng)下的默認(rèn)的Theme不同。其實(shí)wpf控件找不到自定義的樣式時,會從系統(tǒng)獲取樣式,查找順序是,先查找所在的程序集,如果程序集定義了ThemeInfo特性,那么會查看ThemeInfoDictionaryLocation的屬性值,該屬性如果是None則說明沒有特定的主題資源,值為SourceAssembly,說明特定資源定義在程序集內(nèi)部,值為ExternalAssembly則說明在外部,如果還是沒有找到,則程序會在自身的themes/generic.xaml中獲取,在generic.xaml中獲取的其實(shí)就和系統(tǒng)默認(rèn)樣式相關(guān)。

不同xaml所對應(yīng)的系統(tǒng)主題

按鈕案例

C#文件

public class Switch : ToggleButton
{
    static Switch()
    {
        //通過重寫Metadata,控件就會通過程序集themes文件夾下的generic.xaml來尋找系統(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>

自定義控件中常用的知識點(diǎn)

TemplatePart特性

在自定義控件中,有些控件是需要有名稱的以便于調(diào)用,如在重寫的OnApplyTemplate()方法中得到指定的button。這就要求用戶在使用控件時,不能夠修改模板中的名稱。

//應(yīng)用該控件時調(diào)用
public override void OnApplyTemplate()
{
    UpButtonElement = GetTemplateChild("UpButton") as RepeatButton;
    DownButtonElement = GetTemplateChild("DownButton") as RepeatButton;
}

所以在類前面使用特性進(jìn)行標(biāo)注

[TemplatePart(Name = "UpButton", Type = typeof(RepeatButton))]
[TemplatePart(Name = "DownButton", Type = typeof(RepeatButton))]
public class Numeric : Control{}

視覺狀態(tài)的定義與調(diào)用

自定義控件中可以定義視覺狀態(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#中對應(yīng)視覺狀態(tài)的切換

private void UpdateStates(bool useTransitions)
{
    if (IsFocused)
    {
        VisualStateManager.GoToState(this, "Focused", false);
    }
    else
    {
        VisualStateManager.GoToState(this, "Unfocused", false);
    }
}

同時可以在后臺類中使用特性來標(biāo)注

[TemplateVisualState(Name = "Focused", GroupName = "FocusedStates")]
[TemplateVisualState(Name = "Unfocused", GroupName = "FocusedStates")]
public class Numeric : Control{}

其實(shí)完全可以使用Trigger來實(shí)現(xiàn)該功能

以上就是詳解WPF中用戶控件和自定義控件的使用的詳細(xì)內(nèi)容,更多關(guān)于WPF用戶控件 自定義控件的資料請關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

  • C#解決“因為算法不同,客戶端和服務(wù)器無法通信”的問題

    C#解決“因為算法不同,客戶端和服務(wù)器無法通信”的問題

    實(shí)現(xiàn)微信退款功能,我們需要在微信支付商戶后臺申請安全證書,并調(diào)用退款A(yù)PI URL,在調(diào)試過程中為增添返回調(diào)試信息屬性,調(diào)試一切正常,但再次覆蓋的時候,調(diào)用顯示為 “ 因為算法不同,客戶端和服務(wù)器無法通信,” ,本文介紹了C#解決因為算法不同,客戶端和服務(wù)器無法通信的問題
    2024-12-12
  • C#不同類型的成員變量(字段)的默認(rèn)值介紹

    C#不同類型的成員變量(字段)的默認(rèn)值介紹

    雖然C#編譯器為每個類型都設(shè)置了默認(rèn)類型,但作為面向?qū)ο蟮脑O(shè)計原則,我們還是需要對變量進(jìn)行正確的初始化。實(shí)際上這也是C#推薦的做法
    2014-01-01
  • C#讀寫Config配置文件案例

    C#讀寫Config配置文件案例

    這篇文章介紹了C#讀寫Config配置文件的方法,文中通過示例代碼介紹的非常詳細(xì)。對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2022-04-04
  • c#批量整理xml格式示例

    c#批量整理xml格式示例

    這篇文章主要介紹了c#批量整理xml格式示例,win7的x64和x86系統(tǒng)下已驗證通過,需要的朋友可以參考下
    2014-03-03
  • C#使用selenium實(shí)現(xiàn)爬蟲

    C#使用selenium實(shí)現(xiàn)爬蟲

    這篇文章介紹了C#使用selenium實(shí)現(xiàn)爬蟲的方法,文中通過示例代碼介紹的非常詳細(xì)。對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2022-06-06
  • C# 操作符之三元操作符淺析

    C# 操作符之三元操作符淺析

    C# 操作符之三元操作符“?:”是如何使用的呢?C# 操作符之三元操作符“?:”需要注意的是什么呢?那么本文就向你簡單介紹C# 操作符之三元操作符“?:”的基本情況。
    2011-02-02
  • C# 線程同步的方法

    C# 線程同步的方法

    這篇文章主要介紹了C# 線程同步的方法,文中講解非常細(xì)致,代碼幫助大家更好的理解和學(xué)習(xí),感興趣的朋友可以了解下
    2020-08-08
  • 基于switch你可能不知道的一些用法

    基于switch你可能不知道的一些用法

    本篇文章對switch的用法進(jìn)行了詳細(xì)的分析介紹,需要的朋友參考下
    2013-05-05
  • 深入了解c# 匿名類型

    深入了解c# 匿名類型

    這篇文章主要介紹了c# 匿名類型的相關(guān)資料,文中講解非常細(xì)致,代碼幫助大家更好的理解和學(xué)習(xí),感興趣的朋友可以了解下
    2020-07-07
  • C#實(shí)現(xiàn)記事本查找與替換功能

    C#實(shí)現(xiàn)記事本查找與替換功能

    這篇文章主要為大家詳細(xì)介紹了C#實(shí)現(xiàn)記事本查找與替換功能,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2019-03-03

最新評論

博乐市| 高邮市| 卓尼县| 襄垣县| 桐柏县| 普兰店市| 乐山市| 天祝| 兴山县| 印江| 天气| 南部县| 吐鲁番市| 望奎县| 乐都县| 大冶市| 沧源| 蓬溪县| 禹州市| 泉州市| 保定市| 甘孜县| 赣州市| 大港区| 冷水江市| 台东县| 武功县| 开化县| 新化县| 双鸭山市| 三台县| 稻城县| 岗巴县| 吴江市| 周宁县| 平阳县| 阳朔县| 绍兴县| 北宁市| 兴隆县| 平远县|