8

WPF学习笔记(三):WPF为什么需要依赖属性

 3 years ago
source link: https://www.cnblogs.com/ceachy/p/WhyNeedDependencyProperty.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

WPF学习笔记(三):WPF为什么需要依赖属性

(如下片段转自Learning hard的《WPF快速入门系列(2)——深入解析依赖属性》,如有侵权,烦请联系删帖)

WPF中的依赖属性主要有以下三个优点:

  • 依赖属性加入了属性变化通知、限制、验证等功能。这样可以使我们更方便地实现应用,同时大大减少了代码量。许多之前需要写很多代码才能实现的功能,在WPF中可以轻松实现。
  • 节约内存:在WinForm中,每个UI控件的属性都赋予了初始值,这样每个相同的控件在内存中都会保存一份初始值。而WPF依赖属性很好地解决了这个问题,它内部实现使用哈希表存储机制,对多个相同控件的相同属性的值都只保存一份。关于依赖属性如何节约内存的更多内容参考:WPF的依赖属性是怎么节约内存的
  • 支持多种提供对象:可以通过多种方式来设置依赖属性的值。可以配合表达式、样式和绑定来对依赖属性设置值。

(如下片段转自 李霖弢的《WPF 依赖属性和依赖对象》,如果侵权,烦请联系删帖)

WPF的所有UI控件都是依赖对象,控件的属性都是依赖属性。
依赖属性(DependencyProperty)是一种自己可以没有值,但是通过Binding从数据源可以获得值的属性。拥有依赖属性的对象必须为依赖对象(DependencyObject)。
依赖对象具有SetValueGetValue两个方法。
依赖属性的名称通常约定以Property结尾,且只能以DependencyProperty.Register方法创建。
尽管依赖对象没有继承INotifyPropertyChanged,依赖属性在值改变时天生可以通知其Binding对象。

<TextBox x:Name="textbox1" Width="100" Height="50" BorderBrush="Red" Margin="5"></TextBox>
<TextBox x:Name="textbox2" Width="100" Height="50" BorderBrush="Red" Margin="5"></TextBox>
<Button Content="{Binding A}" Width="50"  Click="Button_Click"></Button>
...
Student stu = new Student();
stu.SetBinding(Student.NameProperty, new Binding("Text") { Source = textbox1 });
textbox2.SetBinding(TextBox.TextProperty, new Binding("Name") { Source = stu });
...
public class Student : DependencyObject
{
    public static readonly DependencyProperty NameProperty = DependencyProperty.Register(
        "Name",//依赖属性
        typeof(string),//依赖属性注册类型
        typeof(Student)//依赖对象
    );
    public string Name
    {
        get { return (string)GetValue(NameProperty); }
        set { SetValue(NameProperty, value); }
    }
    //WPF中只有BindingOperations 和 UI元素对象可以直接调用SetBinding,通过该方法封装让依赖属性也可以调用
    public BindingExpressionBase SetBinding(DependencyProperty dp, BindingBase binding)
    {
        return BindingOperations.SetBinding(this, dp, binding);
    }
}

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK