WPF依賴屬性用法詳解
一、什么是依賴屬性
依賴屬性就是一種自己可以沒(méi)有值,并且可以通過(guò)綁定從其他數(shù)據(jù)源獲取值。依賴屬性可支持WPF中的樣式設(shè)置、數(shù)據(jù)綁定、繼承、動(dòng)畫及默認(rèn)值。
將所有的屬性都設(shè)置為依賴屬性并不總是正確的解決方案,具體取決于其應(yīng)用場(chǎng)景。有時(shí),使用私有字段實(shí)現(xiàn)屬性的典型方法便能滿足要求。MSDN中給出了下面幾種應(yīng)用依賴屬性的場(chǎng)景:
- 1. 希望可在樣式中設(shè)置屬性。
- 2. 希望屬性支持?jǐn)?shù)據(jù)綁定。
- 3. 希望可使用動(dòng)態(tài)資源引用設(shè)置屬性。
- 4. 希望從元素樹中的父元素自動(dòng)繼承屬性值。
- 5. 希望屬性可進(jìn)行動(dòng)畫處理。
- 6. 希望屬性系統(tǒng)在屬性系統(tǒng)、環(huán)境或用戶執(zhí)行的操作或者讀取并使用樣式更改了屬性以前的值時(shí)報(bào)告。
- 7. 希望使用已建立的、WPF 進(jìn)程也使用的元數(shù)據(jù)約定,例如報(bào)告更改屬性值時(shí)是否要求布局系統(tǒng)重新編寫元素的可視化對(duì)象。
二、依賴屬性的特點(diǎn)
1、屬性變更通知
無(wú)論什么時(shí)候,只要依賴屬性的值發(fā)生改變,wpf就會(huì)自動(dòng)根據(jù)屬性的元數(shù)據(jù)觸發(fā)一系列的動(dòng)作,這些動(dòng)作可以重新呈現(xiàn)UI元素,也可以更新當(dāng)前的布局,刷新數(shù)據(jù)綁定等等,這種變更的通知最有趣的特點(diǎn)之一就是屬性觸發(fā)器,它可以在屬性值改變的時(shí)候,執(zhí)行一系列自定義的動(dòng)作,而不需要更改任何其他的代碼來(lái)實(shí)現(xiàn)。通過(guò)下面的示例來(lái)演示屬性變更通知
示例:當(dāng)鼠標(biāo)移動(dòng)到Button按鈕上面時(shí),文字的前景色變?yōu)榧t色,離開時(shí)變?yōu)槟J(rèn)顏色黑色,采用傳統(tǒng)方式和依賴屬性兩種方式實(shí)現(xiàn):
(1)、使用傳統(tǒng)方式實(shí)現(xiàn),在Button按鈕上定義MouseEnter和MouseLeave兩個(gè)事件,分別處理鼠標(biāo)移動(dòng)到按鈕上面和離開,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)移動(dòng)到上面,前景色變?yōu)榧t色</Button> </Grid> </Window>
C#后臺(tái)代碼實(shí)現(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)移動(dòng)到按鈕上面 /// </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)使用依賴屬性實(shí)現(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)移動(dòng)到上面,前景色變?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>
使用上面的兩種方式都可以實(shí)現(xiàn)Button按鈕的前景色改變,效果如下:
在判斷屬性IsMouseOver的值為false的時(shí)候,自動(dòng)將Foreground的值改為之前的值,因此就不需要寫IsMouseOver的值為false的時(shí)候,將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)存的使用上是截然不同的,每個(gè)CLR屬性都包含一個(gè)非static的字段,因此當(dāng)我們實(shí)例化一個(gè)類型的時(shí)候,就會(huì)創(chuàng)建該類型所擁有的所有CLR屬性,也就是說(shuō)一個(gè)對(duì)象所占用的內(nèi)存在調(diào)用new操作進(jìn)行實(shí)例化的時(shí)候就已經(jīng)決定了、而wpf允許對(duì)象在創(chuàng)建的時(shí)候并不包含用于存儲(chǔ)數(shù)據(jù)的空間,只保留在需要用到數(shù)據(jù)的時(shí)候能夠獲得該默認(rèn)值,即用其他對(duì)象數(shù)據(jù)或者實(shí)時(shí)分配空間的能力。
三、如何自定義依賴屬性
- 1、聲明依賴屬性變量。依賴屬性的聲明都是通過(guò)public static來(lái)公開一個(gè)靜態(tài)變量,變量的類型必須是DependencyProperty
- 2、在屬性系統(tǒng)中進(jìn)行注冊(cè)。使用DependencyProperty.Register方法來(lái)注冊(cè)依賴屬性,或者是使用DependencyProperty.RegisterReadOnly方法來(lái)注冊(cè)
- 3、使用.NET屬性包裝依賴屬性
在類上實(shí)現(xiàn)屬性時(shí),只要該類派生自 DependencyObject,便可以選擇使用 DependencyProperty 標(biāo)識(shí)符來(lái)標(biāo)示屬性,從而將其設(shè)置為依賴屬性。其語(yǔ)法如下:
public static DependencyProperty TextProperty; TextProperty = DependencyProperty.Register("Text", //屬性名稱 typeof(string), //屬性類型 typeof(TestDependencyPropertyWindow), //該屬性所有者,即將該屬性注冊(cè)到那個(gè)類上 new PropertyMetadata("")); //屬性默認(rèn)值 public string Text { get { return (string)GetValue(TextProperty); } set { SetValue(TextProperty, value); } }
示例:自定義一個(gè)依賴屬性,界面包括一個(gè)TextBox和TextBlock,TextBlock上面字體的前景色隨TextBox里面輸入的顏色而改變,如果TextBox里面輸入的值可以轉(zhuǎn)換成顏色,TextBlock字體的前景色會(huì)顯示輸入的顏色值,如果不能轉(zhuǎn)換,顯示默認(rèn)的前景色。
1、在當(dāng)前項(xiàng)目里面添加一個(gè)WPF版的用戶控件,命名為“MyDependencyProperty”,在MyDependencyProperty.xaml.cs文件里面自定義一個(gè)依賴屬性:
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)行注冊(cè) 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屬性包裝依賴屬性:屬性名稱與注冊(cè)時(shí)候的名稱必須一致, //即屬性名MyColor對(duì)應(yīng)注冊(cè)時(shí)的MyColor public string MyColor { get { return (string)GetValue(MyColorProperty); } set { SetValue(MyColorProperty, value); } } } }
快速定義依賴屬性的快捷方式:
輸入propdp,連續(xù)按兩下Tab健,自動(dòng)生成定義依賴屬性的語(yǔ)法。和輸入cw連續(xù)按兩下Tab健,自動(dòng)生成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里面添加一個(gè)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)建的用戶控件,并添加一個(gè)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è)計(jì)界面顯示的效果:
4、程序運(yùn)行效果:
在TextBox里面輸入正確的顏色值,前景色會(huì)顯示為當(dāng)前輸入的顏色:
在TextBox里面輸入錯(cuò)誤的顏色值,前景色會(huì)顯示為默認(rèn)顏色:
到此這篇關(guān)于WPF依賴屬性用法的文章就介紹到這了。希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
ASP.Net Core對(duì)USB攝像頭進(jìn)行截圖
這篇文章介紹了ASP.Net Core對(duì)USB攝像頭進(jìn)行截圖的方法,文中通過(guò)示例代碼介紹的非常詳細(xì)。對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2022-10-10把ASP.NET MVC項(xiàng)目部署到本地IIS上的完整步驟
最近會(huì)經(jīng)常修改一些網(wǎng)站前端的內(nèi)容,為了方便跟UI和產(chǎn)品交流,需要將自己修改過(guò)的頁(yè)面及時(shí)發(fā)布到測(cè)試機(jī)或者是本地的IIS上。下面這篇文章主要給大家介紹了關(guān)于如何把ASP.NET MVC項(xiàng)目部署到本地IIS上的相關(guān)資料,需要的朋友可以參考下2018-06-06詳解ASP.NET Core部署項(xiàng)目到Ubuntu Server
這篇文章主要介紹了詳解ASP.NET Core部署項(xiàng)目到Ubuntu Server ,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-05-05.NET獲取枚舉DescriptionAttribute描述信息性能改進(jìn)的多種方法
這篇文章主要介紹了.NET獲取枚舉DescriptionAttribute描述信息性能改進(jìn)的多種方法 的相關(guān)資料,需要的朋友可以參考下2016-01-01如何使用.NET Core 選項(xiàng)模式【Options】
這篇文章主要介紹了如何使用.NET Core 選項(xiàng)模式,文中講解非常詳細(xì),代碼幫助大家更好的理解和學(xué)習(xí),感興趣的朋友可以了解下2020-07-07Asp.net 圖片文件防盜鏈(尊重勞動(dòng)成果)及BeginRequest事件學(xué)習(xí)
關(guān)于圖片盜鏈這個(gè)問(wèn)題,畢竟是自己的勞動(dòng)成功,很多人不希望別人就那么輕易地偷走了;反盜鏈的程序其實(shí)很簡(jiǎn)單,熟悉ASP.NET 應(yīng)用程序生命周期的話很容易就可以寫一個(gè),運(yùn)用HttpModule在BeginRequest事件中攔截請(qǐng)求就ok了2013-01-01.NET CORE中使用AutoMapper進(jìn)行對(duì)象映射的方法
這篇文章主要給大家介紹了關(guān)于.NET CORE中使用AutoMapper進(jìn)行對(duì)象映射的相關(guān)資料,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家學(xué)習(xí)或者使用.NET CORE具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2019-04-04ASP.NET中利用存儲(chǔ)過(guò)程實(shí)現(xiàn)模糊查詢
ASP.NET中利用存儲(chǔ)過(guò)程實(shí)現(xiàn)模糊查詢...2006-09-09asp.net使用AJAX實(shí)現(xiàn)無(wú)刷新分頁(yè)
AJAX(Asynchronous JavaScript and XML)是一種進(jìn)行頁(yè)面局部異步刷新的技術(shù)。用AJAX向服務(wù)器發(fā)送請(qǐng)求和獲得服務(wù)器返回的數(shù)據(jù)并且更新到界面中,不是整個(gè)頁(yè)面刷新,而是在頁(yè)面中使用Js創(chuàng)建XMLHTTPRequest對(duì)象來(lái)向服務(wù)器發(fā)出請(qǐng)求以及獲得返回的數(shù)據(jù)。2014-11-11