WPF的依赖属性
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
开发工具与关键技术:VS,C#,WPF
作者:邓晓迪
撰写时间:2019年05月28日
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
- 概述:依赖属性和CRL属性类似,提供一个实例级私有字段的访问封装,通过GetValue和SetValue访问器实现属性的读写操作,最重要一个特点是属性值依赖于一个或者多个数据源,提供这些数据源的方式也可以不同,所以依赖属性就是一种自己可以没有值,并且可以通过绑定从其他数据源获取值。
下面我分别用传统方式和依赖属性方式来实现当鼠标移动到圆上时,给其加上一个大小为40的红色轮廓,离开后变回绿色这一效果,看看它们的区别,效果图如下:
- 使用传统方式实现:XAML代码:
- <Window x:Class="WpfApplication1.MainWindow"
- xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
- xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
- WindowStartupLocation="CenterScreen"
- Title="MainWindow" Height="350" Width="525">
- <Grid>
- <TextBlock TextAlignment="Center" FontSize="16" Margin="0 25 0 0">
- 鼠标移动到圆上,给它一个红色的轮廓
- </TextBlock>
- <Ellipse Height="200" Width="200" Fill="Green" MouseEnter="Ellipse_MouseEnter" MouseLeave="Ellipse_MouseLeave"></Ellipse>
- </Grid>
- </Window>
C#后台代码实现:
- using System.Windows;
- using System.Windows.Input;
- using System.Windows.Media;
- using System.Windows.Shapes;
- namespace WpfApplication1
- {
- /// <summary>
- /// MainWindow.xaml 的交互逻辑
- /// </summary>
- public partial class MainWindow : Window
- {
- public MainWindow()
- {
- InitializeComponent();
- }
- private void Ellipse_MouseEnter(object sender, MouseEventArgs e)
- {
- //创建Ellipse对象
- /*sender 是 private void Ellipse_MouseEnter(object sender,MouseEventArgs e)
- 传入的参数,as 是类型转换
- sender as Ellipse 意思就是将 sender这个object对象转换为Ellipse对象
- */
- Ellipse elp = sender as Ellipse;
- if (elp != null)
- {
- elp.Stroke = Brushes.Red;
- elp.StrokeThickness = 40;
- }
- }
- private void Ellipse_MouseLeave(object sender, MouseEventArgs e)
- {
- Ellipse elp = sender as Ellipse;
- if (elp != null)
- {
- elp.StrokeThickness = 0;
- }
- }
- }
- }
- 使用依赖属性实现:XAML代码:
- <Window x:Class="WpfApplication1.MainWindow"
- xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
- xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
- WindowStartupLocation="CenterScreen"
- Title="MainWindow" Height="350" Width="525">
- <Grid>
- <TextBlock TextAlignment="Center" FontSize="16" Margin="0 25 0 0">
- 鼠标移动到圆上,给它一个红色的轮廓
- </TextBlock>
- <Ellipse Height="200" Width="200" Fill="Green">
- <Ellipse.Style>
- <Style TargetType="Ellipse">
- <!--样式触发器-->
- <Style.Triggers>
- <!--IsMouseOver(鼠标悬停)鼠标位于控件上-->
- <Trigger Property="IsMouseOver" Value="true">
- <!--大小为40的红色轮廓-->
- <Setter Property="Stroke" Value="Red"/>
- <Setter Property="StrokeThickness" Value="40"/>
- </Trigger>
- </Style.Triggers>
- </Style>
- </Ellipse.Style>
- </Ellipse>
- </Grid>
- </Window>
由上面两种方式实现同一效果的代码来看,传统方式比依赖属性多了一个后台代码才能实现,而依赖属性无论什么时候,只要依赖属性的值发生改变,wpf就会自动根据属性的元数据触发一系列的动作,这些动作可以重新呈现UI元素,也可以更新当前的布局,刷新数据绑定等等,这种变更的通知最有趣的特点之一就是属性触发器,它可以在属性值改变的时候,执行一系列自定义的动作,而不需要更改任何其他的代码来实现。