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