国产 无码 综合区,色欲AV无码国产永久播放,无码天堂亚洲国产AV,国产日韩欧美女同一区二区

WPF中用戶(hù)控件和自定義控件

這篇具有很好參考價(jià)值的文章主要介紹了WPF中用戶(hù)控件和自定義控件。希望對(duì)大家有所幫助。如果存在錯(cuò)誤或未考慮完全的地方,請(qǐng)大家不吝賜教,您也可以點(diǎn)擊"舉報(bào)違法"按鈕提交疑問(wèn)。

WPF中用戶(hù)控件和自定義控件

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

  1. 用戶(hù)控件
    • 注重復(fù)合控件的使用,也就是多個(gè)現(xiàn)有控件組成一個(gè)可復(fù)用的控件組
    • XAML和后臺(tái)代碼組成,綁定緊密
    • 不支持模板重寫(xiě)
    • 繼承自UserControl
  2. 自定義控件
    • 完全自己實(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)主題

wpf用戶(hù)控件和自定義控件,WPF,wpf,c#,.net,xaml,ui

按鈕案例

wpf用戶(hù)控件和自定義控件,WPF,wpf,c#,.net,xaml,ui

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)

  1. 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{}
  1. 視覺(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ù)控件和自定義控件的案例,效果如下:

wpf用戶(hù)控件和自定義控件,WPF,wpf,c#,.net,xaml,ui

源碼下載文章來(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)!

本文來(lái)自互聯(lián)網(wǎng)用戶(hù)投稿,該文觀點(diǎn)僅代表作者本人,不代表本站立場(chǎng)。本站僅提供信息存儲(chǔ)空間服務(wù),不擁有所有權(quán),不承擔(dān)相關(guān)法律責(zé)任。如若轉(zhuǎn)載,請(qǐng)注明出處: 如若內(nèi)容造成侵權(quán)/違法違規(guī)/事實(shí)不符,請(qǐng)點(diǎn)擊違法舉報(bào)進(jìn)行投訴反饋,一經(jīng)查實(shí),立即刪除!

領(lǐng)支付寶紅包贊助服務(wù)器費(fèi)用

相關(guān)文章

  • 進(jìn)一步了解WPF UI 實(shí)現(xiàn)XAML語(yǔ)法

    進(jìn)一步了解WPF UI 實(shí)現(xiàn)XAML語(yǔ)法

    Extensible Application Markup Language (XAML) 是一種用于聲明性應(yīng)用程序編程的標(biāo)記語(yǔ)言。 Windows Presentation Foundation (WPF) 實(shí)現(xiàn) XAML 處理器實(shí)現(xiàn)并提供 XAML 語(yǔ)言支持。 WPF 類(lèi)型的實(shí)現(xiàn)為 XAML 表示提供了必要的類(lèi)型支持,從而確保了順暢的集成和高效的運(yùn)行。 在 XAML 標(biāo)記中創(chuàng)建 WPF 應(yīng)用程序

    2024年02月02日
    瀏覽(28)
  • 循序漸進(jìn)介紹基于CommunityToolkit.Mvvm 和HandyControl的WPF應(yīng)用端開(kāi)發(fā)(3)--自定義用戶(hù)控件

    循序漸進(jìn)介紹基于CommunityToolkit.Mvvm 和HandyControl的WPF應(yīng)用端開(kāi)發(fā)(3)--自定義用戶(hù)控件

    在我們創(chuàng)建界面元素的時(shí)候,不管在Vue3+ElementPlus的前端上,還是Winform桌面端上,都是會(huì)利用自定義用戶(hù)控件來(lái)快速重用一些自定義的界面內(nèi)容,對(duì)自定義用戶(hù)控件的封裝處理,也是我們開(kāi)發(fā)WPF應(yīng)用需要熟悉的一環(huán)。本篇隨筆繼續(xù)深入介紹介紹基于CommunityToolkit.Mvvm 和HandyCont

    2024年02月09日
    瀏覽(20)
  • WPF .Net6框架下, 使用 Microsoft.Xaml.Behaviors.Wpf 的Interaction.Triggers特性,實(shí)現(xiàn)ComboBox 在展開(kāi)時(shí),觸發(fā)刷新列表內(nèi)容的動(dòng)作

    ComboBox 在WPF中是常見(jiàn)的控件。 一般情況下,在綁定好數(shù)據(jù)源后,其內(nèi)容是固定的。 當(dāng)然,你也可以實(shí)時(shí)刷新,但這將帶來(lái)較高的資源消耗。 因此有個(gè)折中的辦法: 只在它在展開(kāi)時(shí),自動(dòng)更新列表內(nèi)容。 當(dāng)前文章基于 .Net6框架,其他框架不適用。 這個(gè)是用于平替winform某個(gè)組

    2024年02月09日
    瀏覽(23)
  • WPF 用戶(hù)控件依賴(lài)注入賦值

    WPF 用戶(hù)控件依賴(lài)注入賦值

    我一直想組件化得去開(kāi)發(fā)WPF,因?yàn)槲矣X(jué)得將復(fù)雜問(wèn)題簡(jiǎn)單化是最好的 cs部分 我將復(fù)雜的依賴(lài)注入的代碼進(jìn)行了優(yōu)化,減少了重復(fù)內(nèi)容的輸入。 我現(xiàn)在依賴(lài)屬性擴(kuò)展封裝在一個(gè)靜態(tài)文件里面 記得UserControl.xaml里面綁定你ViewModel。這樣的話有代碼提示 我后面要根據(jù)Vue的單向數(shù)據(jù)

    2024年02月07日
    瀏覽(19)
  • WPF自定義控件

    WPF自定義控件

    方式一:基于現(xiàn)有控件進(jìn)行擴(kuò)展,如基于button進(jìn)行擴(kuò)展,UI可直接用xmal進(jìn)行編輯設(shè)計(jì),邏輯用xaml.cs進(jìn)行編輯 方法二:直接創(chuàng)建wpf自定義控件 本文用方法二開(kāi)展自定義控件?。?! 1.自定義控件的內(nèi)容在代碼cs文件中,自定義控件繼承自Control,ui界面可在Genric.xaml中定義。 2.在

    2024年02月11日
    瀏覽(30)
  • WPF自定義按鈕控件

    WPF自定義按鈕控件

    在平時(shí)的WPF應(yīng)用中,系統(tǒng)提供的按鈕控件確實(shí)可以實(shí)現(xiàn)正常的邏輯,但是從視覺(jué)方面看的話,確實(shí)不夠美觀,而且每個(gè)項(xiàng)目的UI設(shè)計(jì)不盡相同。那么自定義按鈕控件就是必須的了,網(wǎng)上查找了很多自定義按鈕控件的辦法,但每次都是寫(xiě)到一半就報(bào)錯(cuò)。在參考了多個(gè)技術(shù)貼之后

    2024年02月08日
    瀏覽(22)
  • 如何使用 WPF 用戶(hù)控件關(guān)閉父窗口

    How to close parent windows using WPF User Control 如何使用 WPF 用戶(hù)控件關(guān)閉父窗口 【問(wèn)題描述】 假設(shè)有兩個(gè)WPF窗口:window1和window2。 window1有一個(gè)按鈕,單擊此按鈕將打開(kāi)window2。window2包含一個(gè)用戶(hù)控件。此用戶(hù)控件有一個(gè)用于關(guān)閉window2的按鈕。 怎樣才能實(shí)現(xiàn)這個(gè)場(chǎng)景呢? 【解決方案

    2024年02月15日
    瀏覽(38)
  • wpf 自定義combox控件

    wpf 自定義combox控件

    關(guān)鍵步驟 1、新建usercontrol使用基本的控件進(jìn)行設(shè)計(jì) 2、依賴(lài)屬性的定義,目的:外部調(diào)用時(shí)候能夠使用屬性進(jìn)行控件樣式的控制 例如 Width=\\\"200\\\" DisplayMemberPath=\\\"Name\\\" SelectedItem=\\\"{Binding SelectedItem,Mode=TwoWay}\\\" SelectionChanged=\\\"{Binding ProjectSelectCommand}\\\" CommandParameter=\\\"{Binding ElementName = Projec

    2024年02月09日
    瀏覽(22)
  • 【.NET深呼吸】用代碼寫(xiě)WPF控件模板

    【.NET深呼吸】用代碼寫(xiě)WPF控件模板

    這一次咱們來(lái)探究一下怎么用純代碼寫(xiě) WPF 模板。模板有個(gè)共同基類(lèi)?FrameworkTemplate,數(shù)據(jù)模板、控件模板等是從此類(lèi)派生的,因此,該類(lèi)已定義了一些通用成員。 用代碼構(gòu)建模板,重要的成員是?VisualTree 屬性,它的類(lèi)型是?FrameworkElementFactory??梢?jiàn),模板不是直接創(chuàng)建可視化

    2024年02月09日
    瀏覽(20)
  • WPF grid控件定義行和列

    WPF grid控件定義行和列

    在此已經(jīng)學(xué)習(xí)了wpf Grid控件, WPF布局控件Grid的基本使用 - 使用kaxaml_bcbobo21cn的博客-CSDN博客 下面繼續(xù)學(xué)習(xí); 定義3行3列的基本代碼如下;為了看清效果,設(shè)置 ShowGridLines=\\\"True\\\"; ? 減少一列,效果如下; ? 只有行,沒(méi)有列; ? 指定第一列的寬度; ? 第一列指定寬度,剩下2列

    2024年02月13日
    瀏覽(28)

覺(jué)得文章有用就打賞一下文章作者

支付寶掃一掃打賞

博客贊助

微信掃一掃打賞

請(qǐng)作者喝杯咖啡吧~博客贊助

支付寶掃一掃領(lǐng)取紅包,優(yōu)惠每天領(lǐng)

二維碼1

領(lǐng)取紅包

二維碼2

領(lǐng)紅包