WPF依赖属性用法详解

2022-04-17 05:52:15

一、什么是依赖属性

依赖属性就是一种自己可以没有值,并且可以通过绑定从其他数据源获取值。依赖属性可支持WPF中的样式设置、数据绑定、继承、动画及默认值。

将所有的属性都设置为依赖属性并不总是正确的解决方案,具体取决于其应用场景。有时,使用私有字段实现属性的典型方法便能满足要求。MSDN中给出了下面几种应用依赖属性的场景:

1. 希望可在样式中设置属性。2. 希望属性支持数据绑定。3. 希望可使用动态资源引用设置属性。4. 希望从元素树中的父元素自动继承属性值。5. 希望属性可进行动画处理。6. 希望属性系统在属性系统、环境或用户执行的操作或者读取并使用样式更改了属性以前的值时报告。7. 希望使用已建立的、WPF 进程也使用的元数据约定,例如报告更改属性值时是否要求布局系统重新编写元素的可视化对象。

二、依赖属性的特点

1、属性变更通知

无论什么时候,只要依赖属性的值发生改变,wpf就会自动根据属性的元数据触发一系列的动作,这些动作可以重新呈现UI元素,也可以更新当前的布局,刷新数据绑定等等,这种变更的通知最有趣的特点之一就是属性触发器,它可以在属性值改变的时候,执行一系列自定义的动作,而不需要更改任何其他的代码来实现。通过下面的示例来演示属性变更通知

示例:当鼠标移动到Button按钮上面时,文字的前景色变为红色,离开时变为默认颜色黑色,采用传统方式和依赖属性两种方式实现:

(1)、使用传统方式实现,在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" >鼠标移动到上面,前景色变为红色</Button>            </Grid></Window>

C#后台代码实现:

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)使用依赖属性实现,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">鼠标移动到上面,前景色变为红色            <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>

使用上面的两种方式都可以实现Button按钮的前景色改变,效果如下:

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、在属性系统中进行注册 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,连续按两下Tab健,自动生成定义依赖属性的语法。和输入cw连续按两下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里面引用新创建的用户控件,并添加一个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>

在设计界面显示的效果:

WPF依赖属性用法详解

4、程序运行效果:

在TextBox里面输入正确的颜色值,前景色会显示为当前输入的颜色:

WPF依赖属性用法详解

在TextBox里面输入错误的颜色值,前景色会显示为默认颜色:

WPF依赖属性用法详解

到此这篇关于WPF依赖属性用法的文章就介绍到这了。希望对大家的学习有所帮助,也希望大家多多支持我们。