欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

WPF依賴屬性用法詳解

 更新時間:2022年02月25日 11:32:31   作者:.NET開發(fā)菜鳥  
本文詳細(xì)講解了WPF依賴屬性的用法,文中通過示例代碼介紹的非常詳細(xì)。對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下

一、什么是依賴屬性

依賴屬性就是一種自己可以沒有值,并且可以通過綁定從其他數(shù)據(jù)源獲取值。依賴屬性可支持WPF中的樣式設(shè)置、數(shù)據(jù)綁定、繼承、動畫及默認(rèn)值。

將所有的屬性都設(shè)置為依賴屬性并不總是正確的解決方案,具體取決于其應(yīng)用場景。有時,使用私有字段實現(xiàn)屬性的典型方法便能滿足要求。MSDN中給出了下面幾種應(yīng)用依賴屬性的場景:

  • 1. 希望可在樣式中設(shè)置屬性。
  • 2. 希望屬性支持?jǐn)?shù)據(jù)綁定。
  • 3. 希望可使用動態(tài)資源引用設(shè)置屬性。
  • 4. 希望從元素樹中的父元素自動繼承屬性值。
  • 5. 希望屬性可進(jìn)行動畫處理。
  • 6. 希望屬性系統(tǒng)在屬性系統(tǒng)、環(huán)境或用戶執(zhí)行的操作或者讀取并使用樣式更改了屬性以前的值時報告。
  • 7. 希望使用已建立的、WPF 進(jìn)程也使用的元數(shù)據(jù)約定,例如報告更改屬性值時是否要求布局系統(tǒng)重新編寫元素的可視化對象。

二、依賴屬性的特點(diǎn)

1、屬性變更通知

無論什么時候,只要依賴屬性的值發(fā)生改變,wpf就會自動根據(jù)屬性的元數(shù)據(jù)觸發(fā)一系列的動作,這些動作可以重新呈現(xiàn)UI元素,也可以更新當(dāng)前的布局,刷新數(shù)據(jù)綁定等等,這種變更的通知最有趣的特點(diǎn)之一就是屬性觸發(fā)器,它可以在屬性值改變的時候,執(zhí)行一系列自定義的動作,而不需要更改任何其他的代碼來實現(xiàn)。通過下面的示例來演示屬性變更通知

示例:當(dāng)鼠標(biāo)移動到Button按鈕上面時,文字的前景色變?yōu)榧t色,離開時變?yōu)槟J(rèn)顏色黑色,采用傳統(tǒng)方式和依賴屬性兩種方式實現(xiàn):

(1)、使用傳統(tǒng)方式實現(xiàn),在Button按鈕上定義MouseEnter和MouseLeave兩個事件,分別處理鼠標(biāo)移動到按鈕上面和離開,XAML界面代碼:

<Window x:Class="WpfDemo.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="Grid面板" Height="237" Width="525" WindowStartupLocation="CenterScreen">
    <Grid >              
        <Button Height="30" Width="200" MouseEnter="Button_MouseEnter" MouseLeave="Button_MouseLeave" >鼠標(biāo)移動到上面,前景色變?yōu)榧t色</Button>        
    </Grid>
</Window>

C#后臺代碼實現(xiàn):

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace WpfDemo
{
    /// <summary>
    /// MainWindow.xaml 的交互邏輯
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        /// <summary>
        /// 鼠標(biāo)移動到按鈕上面
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Button_MouseEnter(object sender, MouseEventArgs e)
        {
            Button btn = sender as Button;
            if (btn != null)
            {
                btn.Foreground = Brushes.Red;
            }
        }

        /// <summary>
        /// 鼠標(biāo)離開按鈕
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Button_MouseLeave(object sender, MouseEventArgs e)
        {
            Button btn = sender as Button;
            if (btn != null)
            {
                btn.Foreground = Brushes.Black;
            }
        }
    }
}

(2)使用依賴屬性實現(xiàn),XAML界面代碼:

<Window x:Class="WpfDemo.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="Grid面板" Height="237" Width="525" WindowStartupLocation="CenterScreen">
    <Grid >
        <Button Height="30" Width="200">鼠標(biāo)移動到上面,前景色變?yōu)榧t色
            <Button.Style>
                <Style TargetType="Button">
                    <Style.Triggers>
                        <Trigger Property="IsMouseOver" Value="true">
                            <Setter Property="Foreground" Value="Red"></Setter>
                        </Trigger>
                    </Style.Triggers>
                </Style>
            </Button.Style>
        </Button>
    </Grid>
</Window>

使用上面的兩種方式都可以實現(xiàn)Button按鈕的前景色改變,效果如下:

在判斷屬性IsMouseOver的值為false的時候,自動將Foreground的值改為之前的值,因此就不需要寫IsMouseOver的值為false的時候,將Foreground的值改為Black。

2、屬性值繼承

是指屬性值自頂向下沿著元素樹進(jìn)行傳遞。

<Window x:Class="WpfDemo.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="依賴屬性" Height="237" Width="525" FontSize="18" WindowStartupLocation="CenterScreen">
    <Grid >
        <StackPanel>
            <TextBlock>我使用的是繼承的fontsize</TextBlock>
            <TextBlock FontSize="11">我使用的是自己的fontsize</TextBlock>
        </StackPanel>
    </Grid>
</Window>

界面運(yùn)行效果:

3、節(jié)省內(nèi)存空間

依賴屬性和CLR屬性在內(nèi)存的使用上是截然不同的,每個CLR屬性都包含一個非static的字段,因此當(dāng)我們實例化一個類型的時候,就會創(chuàng)建該類型所擁有的所有CLR屬性,也就是說一個對象所占用的內(nèi)存在調(diào)用new操作進(jìn)行實例化的時候就已經(jīng)決定了、而wpf允許對象在創(chuàng)建的時候并不包含用于存儲數(shù)據(jù)的空間,只保留在需要用到數(shù)據(jù)的時候能夠獲得該默認(rèn)值,即用其他對象數(shù)據(jù)或者實時分配空間的能力。

三、如何自定義依賴屬性

  • 1、聲明依賴屬性變量。依賴屬性的聲明都是通過public static來公開一個靜態(tài)變量,變量的類型必須是DependencyProperty
  • 2、在屬性系統(tǒng)中進(jìn)行注冊。使用DependencyProperty.Register方法來注冊依賴屬性,或者是使用DependencyProperty.RegisterReadOnly方法來注冊
  • 3、使用.NET屬性包裝依賴屬性

在類上實現(xiàn)屬性時,只要該類派生自 DependencyObject,便可以選擇使用 DependencyProperty 標(biāo)識符來標(biāo)示屬性,從而將其設(shè)置為依賴屬性。其語法如下:

public static DependencyProperty TextProperty;
       TextProperty =
       DependencyProperty.Register("Text", //屬性名稱
       typeof(string), //屬性類型
       typeof(TestDependencyPropertyWindow), //該屬性所有者,即將該屬性注冊到那個類上
       new PropertyMetadata("")); //屬性默認(rèn)值

public string Text
{
   get { return (string)GetValue(TextProperty); }
   set { SetValue(TextProperty, value); }
}

 示例:自定義一個依賴屬性,界面包括一個TextBox和TextBlock,TextBlock上面字體的前景色隨TextBox里面輸入的顏色而改變,如果TextBox里面輸入的值可以轉(zhuǎn)換成顏色,TextBlock字體的前景色會顯示輸入的顏色值,如果不能轉(zhuǎn)換,顯示默認(rèn)的前景色。

1、在當(dāng)前項目里面添加一個WPF版的用戶控件,命名為“MyDependencyProperty”,在MyDependencyProperty.xaml.cs文件里面自定義一個依賴屬性:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace WpfDemo
{
    /// <summary>
    /// MyDependencyProperty.xaml 的交互邏輯
    /// </summary>
    public partial class MyDependencyProperty : UserControl
    {
        public MyDependencyProperty()
        {
            InitializeComponent();
        }

        //1、聲明依賴屬性變量
        public static readonly DependencyProperty MyColorProperty;

        //2、在屬性系統(tǒng)中進(jìn)行注冊
        static MyDependencyProperty()
        {
            MyColorProperty = DependencyProperty.Register("MyColor", typeof(string), typeof(MyDependencyProperty),
                new PropertyMetadata("Red", (s, e) =>
                {
                    var mdp = s as MyDependencyProperty;
                    if (mdp != null)
                    {
                        try
                        {
                            var color = (Color)ColorConverter.ConvertFromString(e.NewValue.ToString());
                            mdp.Foreground = new SolidColorBrush(color);
                        }
                        catch
                        {
                            mdp.Foreground = new SolidColorBrush(Colors.Black);
                        }
                    }

                }));
        }

        //3、使用.NET屬性包裝依賴屬性:屬性名稱與注冊時候的名稱必須一致,
        //即屬性名MyColor對應(yīng)注冊時的MyColor
        public string MyColor
        {
            get
            {
                return (string)GetValue(MyColorProperty);
            }
            set
            {
                SetValue(MyColorProperty, value);
            }
        }
    }
}

快速定義依賴屬性的快捷方式:

輸入propdp,連續(xù)按兩下Tab健,自動生成定義依賴屬性的語法。和輸入cw連續(xù)按兩下Tab健,自動生成Console.Write()一樣。

public int MyProperty
        {
            get { return (int)GetValue(MyPropertyProperty); }
            set { SetValue(MyPropertyProperty, value); }
        }

        // Using a DependencyProperty as the backing store for MyProperty.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty MyPropertyProperty =
            DependencyProperty.Register("MyProperty", typeof(int), typeof(ownerclass), new PropertyMetadata(0));

2、在MyDependencyProperty.xaml里面添加一個TextBlock

<UserControl x:Class="WpfDemo.MyDependencyProperty"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             mc:Ignorable="d"
             d:DesignHeight="300" d:DesignWidth="300">
    <Grid>
        <TextBlock>我是自定義的依賴屬性</TextBlock>
    </Grid>
</UserControl>

3、在MainWindow.xaml里面引用新創(chuàng)建的用戶控件,并添加一個TextBox,用于輸入顏色值,并將自定義的依賴屬性MyColor綁定到TextBox

<Window x:Class="WpfDemo.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:p="clr-namespace:WpfDemo"
        Title="依賴屬性" Height="237" Width="525" WindowStartupLocation="CenterScreen">
    <Grid >
        <StackPanel>
            <TextBox Name="tbColor"></TextBox>
            <p:MyDependencyProperty MyColor="{Binding Path=Text,ElementName=tbColor}" ></p:MyDependencyProperty>
        </StackPanel>
    </Grid>
</Window>

在設(shè)計界面顯示的效果:

4、程序運(yùn)行效果:

在TextBox里面輸入正確的顏色值,前景色會顯示為當(dāng)前輸入的顏色:

在TextBox里面輸入錯誤的顏色值,前景色會顯示為默認(rèn)顏色:

到此這篇關(guān)于WPF依賴屬性用法的文章就介紹到這了。希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

  • ASP.Net Core對USB攝像頭進(jìn)行截圖

    ASP.Net Core對USB攝像頭進(jìn)行截圖

    這篇文章介紹了ASP.Net Core對USB攝像頭進(jìn)行截圖的方法,文中通過示例代碼介紹的非常詳細(xì)。對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2022-10-10
  • 把ASP.NET MVC項目部署到本地IIS上的完整步驟

    把ASP.NET MVC項目部署到本地IIS上的完整步驟

    最近會經(jīng)常修改一些網(wǎng)站前端的內(nèi)容,為了方便跟UI和產(chǎn)品交流,需要將自己修改過的頁面及時發(fā)布到測試機(jī)或者是本地的IIS上。下面這篇文章主要給大家介紹了關(guān)于如何把ASP.NET MVC項目部署到本地IIS上的相關(guān)資料,需要的朋友可以參考下
    2018-06-06
  • 詳解ASP.NET Core部署項目到Ubuntu Server

    詳解ASP.NET Core部署項目到Ubuntu Server

    這篇文章主要介紹了詳解ASP.NET Core部署項目到Ubuntu Server ,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2017-05-05
  • .NET獲取枚舉DescriptionAttribute描述信息性能改進(jìn)的多種方法

    .NET獲取枚舉DescriptionAttribute描述信息性能改進(jìn)的多種方法

    這篇文章主要介紹了.NET獲取枚舉DescriptionAttribute描述信息性能改進(jìn)的多種方法 的相關(guān)資料,需要的朋友可以參考下
    2016-01-01
  • 如何使用.NET Core 選項模式【Options】

    如何使用.NET Core 選項模式【Options】

    這篇文章主要介紹了如何使用.NET Core 選項模式,文中講解非常詳細(xì),代碼幫助大家更好的理解和學(xué)習(xí),感興趣的朋友可以了解下
    2020-07-07
  • VS2013的Browser Link引起的問題

    VS2013的Browser Link引起的問題

    這篇文章主要為大家詳細(xì)介紹了VS2013的Browser Link引起的問題,以及Browser Link問題的解決方法,感興趣的小伙伴們可以參考一下
    2016-07-07
  • Asp.net 圖片文件防盜鏈(尊重勞動成果)及BeginRequest事件學(xué)習(xí)

    Asp.net 圖片文件防盜鏈(尊重勞動成果)及BeginRequest事件學(xué)習(xí)

    關(guān)于圖片盜鏈這個問題,畢竟是自己的勞動成功,很多人不希望別人就那么輕易地偷走了;反盜鏈的程序其實很簡單,熟悉ASP.NET 應(yīng)用程序生命周期的話很容易就可以寫一個,運(yùn)用HttpModule在BeginRequest事件中攔截請求就ok了
    2013-01-01
  • .NET CORE中使用AutoMapper進(jìn)行對象映射的方法

    .NET CORE中使用AutoMapper進(jìn)行對象映射的方法

    這篇文章主要給大家介紹了關(guān)于.NET CORE中使用AutoMapper進(jìn)行對象映射的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對大家學(xué)習(xí)或者使用.NET CORE具有一定的參考學(xué)習(xí)價值,需要的朋友們下面來一起學(xué)習(xí)學(xué)習(xí)吧
    2019-04-04
  • ASP.NET中利用存儲過程實現(xiàn)模糊查詢

    ASP.NET中利用存儲過程實現(xiàn)模糊查詢

    ASP.NET中利用存儲過程實現(xiàn)模糊查詢...
    2006-09-09
  • asp.net使用AJAX實現(xiàn)無刷新分頁

    asp.net使用AJAX實現(xiàn)無刷新分頁

    AJAX(Asynchronous JavaScript and XML)是一種進(jìn)行頁面局部異步刷新的技術(shù)。用AJAX向服務(wù)器發(fā)送請求和獲得服務(wù)器返回的數(shù)據(jù)并且更新到界面中,不是整個頁面刷新,而是在頁面中使用Js創(chuàng)建XMLHTTPRequest對象來向服務(wù)器發(fā)出請求以及獲得返回的數(shù)據(jù)。
    2014-11-11

最新評論