WPF依賴屬性用法詳解
一、什么是依賴屬性
依賴屬性就是一種自己可以沒有值,并且可以通過綁定從其他數(shù)據(jù)源獲取值。依賴屬性可支持WPF中的樣式設置、數(shù)據(jù)綁定、繼承、動畫及默認值。
將所有的屬性都設置為依賴屬性并不總是正確的解決方案,具體取決于其應用場景。有時,使用私有字段實現(xiàn)屬性的典型方法便能滿足要求。MSDN中給出了下面幾種應用依賴屬性的場景:
- 1. 希望可在樣式中設置屬性。
- 2. 希望屬性支持數(shù)據(jù)綁定。
- 3. 希望可使用動態(tài)資源引用設置屬性。
- 4. 希望從元素樹中的父元素自動繼承屬性值。
- 5. 希望屬性可進行動畫處理。
- 6. 希望屬性系統(tǒng)在屬性系統(tǒng)、環(huán)境或用戶執(zhí)行的操作或者讀取并使用樣式更改了屬性以前的值時報告。
- 7. 希望使用已建立的、WPF 進程也使用的元數(shù)據(jù)約定,例如報告更改屬性值時是否要求布局系統(tǒng)重新編寫元素的可視化對象。
二、依賴屬性的特點
1、屬性變更通知
無論什么時候,只要依賴屬性的值發(fā)生改變,wpf就會自動根據(jù)屬性的元數(shù)據(jù)觸發(fā)一系列的動作,這些動作可以重新呈現(xiàn)UI元素,也可以更新當前的布局,刷新數(shù)據(jù)綁定等等,這種變更的通知最有趣的特點之一就是屬性觸發(fā)器,它可以在屬性值改變的時候,執(zhí)行一系列自定義的動作,而不需要更改任何其他的代碼來實現(xiàn)。通過下面的示例來演示屬性變更通知
示例:當鼠標移動到Button按鈕上面時,文字的前景色變?yōu)榧t色,離開時變?yōu)槟J顏色黑色,采用傳統(tǒng)方式和依賴屬性兩種方式實現(xiàn):
(1)、使用傳統(tǒng)方式實現(xiàn),在Button按鈕上定義MouseEnter和MouseLeave兩個事件,分別處理鼠標移動到按鈕上面和離開,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" >鼠標移動到上面,前景色變?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>
/// 鼠標移動到按鈕上面
/// </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>
/// 鼠標離開按鈕
/// </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">鼠標移動到上面,前景色變?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、屬性值繼承
是指屬性值自頂向下沿著元素樹進行傳遞。
<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>界面運行效果:

3、節(jié)省內存空間
依賴屬性和CLR屬性在內存的使用上是截然不同的,每個CLR屬性都包含一個非static的字段,因此當我們實例化一個類型的時候,就會創(chuàng)建該類型所擁有的所有CLR屬性,也就是說一個對象所占用的內存在調用new操作進行實例化的時候就已經決定了、而wpf允許對象在創(chuàng)建的時候并不包含用于存儲數(shù)據(jù)的空間,只保留在需要用到數(shù)據(jù)的時候能夠獲得該默認值,即用其他對象數(shù)據(jù)或者實時分配空間的能力。
三、如何自定義依賴屬性
- 1、聲明依賴屬性變量。依賴屬性的聲明都是通過public static來公開一個靜態(tài)變量,變量的類型必須是DependencyProperty
- 2、在屬性系統(tǒng)中進行注冊。使用DependencyProperty.Register方法來注冊依賴屬性,或者是使用DependencyProperty.RegisterReadOnly方法來注冊
- 3、使用.NET屬性包裝依賴屬性
在類上實現(xiàn)屬性時,只要該類派生自 DependencyObject,便可以選擇使用 DependencyProperty 標識符來標示屬性,從而將其設置為依賴屬性。其語法如下:
public static DependencyProperty TextProperty;
TextProperty =
DependencyProperty.Register("Text", //屬性名稱
typeof(string), //屬性類型
typeof(TestDependencyPropertyWindow), //該屬性所有者,即將該屬性注冊到那個類上
new PropertyMetadata("")); //屬性默認值
public string Text
{
get { return (string)GetValue(TextProperty); }
set { SetValue(TextProperty, value); }
}示例:自定義一個依賴屬性,界面包括一個TextBox和TextBlock,TextBlock上面字體的前景色隨TextBox里面輸入的顏色而改變,如果TextBox里面輸入的值可以轉換成顏色,TextBlock字體的前景色會顯示輸入的顏色值,如果不能轉換,顯示默認的前景色。
1、在當前項目里面添加一個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)中進行注冊
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對應注冊時的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>在設計界面顯示的效果:

4、程序運行效果:
在TextBox里面輸入正確的顏色值,前景色會顯示為當前輸入的顏色:

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

到此這篇關于WPF依賴屬性用法的文章就介紹到這了。希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
詳解ASP.NET Core部署項目到Ubuntu Server
這篇文章主要介紹了詳解ASP.NET Core部署項目到Ubuntu Server ,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-05-05
.NET獲取枚舉DescriptionAttribute描述信息性能改進的多種方法
這篇文章主要介紹了.NET獲取枚舉DescriptionAttribute描述信息性能改進的多種方法 的相關資料,需要的朋友可以參考下2016-01-01
Asp.net 圖片文件防盜鏈(尊重勞動成果)及BeginRequest事件學習
關于圖片盜鏈這個問題,畢竟是自己的勞動成功,很多人不希望別人就那么輕易地偷走了;反盜鏈的程序其實很簡單,熟悉ASP.NET 應用程序生命周期的話很容易就可以寫一個,運用HttpModule在BeginRequest事件中攔截請求就ok了2013-01-01
.NET CORE中使用AutoMapper進行對象映射的方法
這篇文章主要給大家介紹了關于.NET CORE中使用AutoMapper進行對象映射的相關資料,文中通過示例代碼介紹的非常詳細,對大家學習或者使用.NET CORE具有一定的參考學習價值,需要的朋友們下面來一起學習學習吧2019-04-04

