依赖属性
依赖属性基础
依赖属性是具有借用其他对象的数据的能力,具有依赖属性的对象为依赖对象。WPF所有UI都是依赖对象。
只有依赖属性才能做为Bingding的源或目标。
DependencyObject具有GetValue()和SetValue()两个方法。
自定义一个依赖对象
public class Student3: DependencyObject//必须继承DependencyObject才能成为一个依赖对象
{
// 定义依赖属性标准格式
public static readonly DependencyProperty NameProperty =
DependencyProperty.Register("Name", typeof(string), typeof(Student3), new PropertyMetadata("无名"));
//Name是依赖属性NameProperty的包装器,对外暴漏被使用
public string Name//在VS中输入propdp再按两次tab可以快捷输入
{
get { return (string)GetValue(NameProperty); }
set { SetValue(NameProperty, value); }
}
//使其也像UI一样有个SetBingding方法
public BindingExpressionBase SetBingding(DependencyProperty dp, BindingBase binding)
{
return BindingOperations.SetBinding(this, dp, binding);
}
}
调用:
public partial class property : Window
{
//一定要定义在外面,要不然textBox1改变了textBox2也不会自动变
Student3 su = new Student3();
public property()
{
InitializeComponent();
su.SetBingding(Student3.NameProperty, new Binding("Text") { Source = textBox1 });
//Student3没为实现INotifyPropertyChanged接口同样也可以得到通知
textBox2.SetBinding(TextBox.TextProperty, new Binding("Name") { Source = su });
}
}
其实依赖属性的值并不是保存在NameProperty 中,而是通过CLR属性名和宿主类型名称从全局的Hashtable中检索或保存的。
附加属性基础
附加属性本质还是依赖属性。一个对象在不同环境后才具有的属性就叫附加属性。
如人类Human在学校有班级属性,在公司就有部门的属性。
<Label x:Name="label" Grid.Row="1"/>
定义以及使用例子:
public class Human : DependencyObject
{
//一定要继承DependencyObject成为依赖对象
}
public class School : DependencyObject
{
// 标准定义格式,与信赖属性差不多。 使用“propa”+两次tab可以快捷生成
public static readonly DependencyProperty GradeProperty =
DependencyProperty.RegisterAttached("Grade", typeof(string), typeof(School), new PropertyMetadata("无班级"));
public static string GetGrade(DependencyObject obj)
{
return (string)obj.GetValue(GradeProperty);
}
public static void SetGradeP(DependencyObject obj, string value)
{
obj.SetValue(GradeProperty, value);
}
}
调用:
Human human = new Human();
School.SetGrade(human, "五年级");
string grade = School.GetGrade(human);
//可以得到grade的值为五年级
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构