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

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

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

介紹

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

1.用戶控件

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

2.自定義控件

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

用戶控件

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

后臺(tái)代碼

//根據(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)擊添加自定義控件后,會(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ò)重寫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特性

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

//應(yīng)用該控件時(shí)調(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{}

視覺(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)標(biāo)注

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

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

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

相關(guān)文章

  • C#解決“因?yàn)樗惴ú煌?,客戶端和服?wù)器無(wú)法通信”的問(wèn)題

    C#解決“因?yàn)樗惴ú煌?,客戶端和服?wù)器無(wú)法通信”的問(wèn)題

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

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

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

    C#讀寫Config配置文件案例

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

    c#批量整理xml格式示例

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

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

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

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

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

    C# 線程同步的方法

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

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

    本篇文章對(duì)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)記事本查找與替換功能,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2019-03-03

最新評(píng)論

麦盖提县| 静安区| 永年县| 公主岭市| 体育| 土默特左旗| 云阳县| 尉犁县| 和田市| 饶河县| 穆棱市| 高阳县| 中超| 台北市| 新干县| 嵊泗县| 沁源县| 修文县| 十堰市| 太仆寺旗| 东海县| 大宁县| 炉霍县| 砀山县| 大理市| 海宁市| 昭苏县| 沅陵县| 华坪县| 庐江县| 观塘区| 达孜县| 阿巴嘎旗| 阳西县| 嘉祥县| 肃北| 巴楚县| 山阴县| 石嘴山市| 宕昌县| 苍梧县|