WPF 依赖项属性
WPF中的依赖项属性
对比与C#的属性。依赖属性是为WPF创建的。WPF很多情况下都在使用依赖属性。
1 依赖属性加入了属性变化通知,限制,验证功能。
2 节约内存
3 通过多种方式设置依赖属性的值
把属性换成依赖属性
1 依赖属性继承自 DependencyObject
2 使用public static 声明一个变量
public static readonly DependencyProperty MyPropertyProperty
3 再进行 Register 注册
public class Person: DependencyObject { static Person() { } 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(Person), new PropertyMetadata(0)); }
依赖属性的继承
<Window x:Class="WpfApp1.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:local="clr-namespace:WpfApp1" mc:Ignorable="d" FontSize="30" Title="MainWindow" Height="450" Width="800"> <StackPanel> <TextBlock Text="123"/> <TextBlock Text="123" FontSize="15"/> </StackPanel> </Window>
window上的fontsize会影响到所有的子元素字体大小。
通过AddOwer进行依赖属性继承
public class CustomStackPanel:StackPanel { static CustomStackPanel() { MyPropertyProperty = DependencyProperty.Register("MyProperty", typeof(string), typeof(CustomStackPanel), new FrameworkPropertyMetadata("23333", FrameworkPropertyMetadataOptions.Inherits)); } public string MyProperty { get => (string)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; } public class CustomButton : Button { private static readonly DependencyProperty MyDependencyProperty; static CustomButton() { MyDependencyProperty = CustomStackPanel.MyPropertyProperty.AddOwner(typeof(CustomButton), new FrameworkPropertyMetadata("233333", FrameworkPropertyMetadataOptions.Inherits)); } public string MyProperty { get => (string) GetValue(MyDependencyProperty); set => SetValue(MyDependencyProperty, value); } }
只读依赖属性
DependencyProperty.RegisterAttachedReadOnly
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异
· 三行代码完成国际化适配,妙~啊~