WPF依赖属性和依赖属性的包装器:

依赖属性是WPF(Windows Presentation Foundation)中的一种特殊类型的属性,特别适用于内存使用优化和属性值继承。依赖属性的定义包括以下几个步骤:

使用 DependencyProperty.Register 方法注册依赖属性。

该方法需要四个参数:

第一个参数是依赖属性的名称,这里为 "Age"。

第二个参数是依赖属性的数据类型,这里为 typeof(int)。

第三个参数是拥有该依赖属性的类的类型,这里为 typeof(DataModel)。

第四个参数是属性的元数据,通过 PropertyMetadata 类传递,这里设置了默认值 18。

依赖属性通过 GetValue 和 SetValue 方法进行访问和修改,而不是通过简单的getter和setter,这使得它们可以参与WPF的数据绑定、样式继承等高级功能

csharp 复制代码
 public static readonly DependencyProperty AgeProperty =
DependencyProperty.Register("Age", typeof(int), typeof(MainWindow), new PropertyMetadata(18));

// 包装器:把依赖属性AgeProperty包装一下,可以理解成给依赖属性AgeProperty添加一个"外壳"。

// 添加"外壳"后让依赖属性用起来和普通属性一个用法。

// B。依赖属性的包装器:

csharp 复制代码
 public int Age
 {
     get { return (int)GetValue(AgeProperty); }
     set { SetValue(AgeProperty, value); }
 }

C. 属性的使用

给当前的XAML文档绑定上下文写法1:默认支持智能感知

只有给XAML文档绑定了上下文后,XAML文档中才能使用上下文对象中提供的数据(属性等)

csharp 复制代码
<Window.DataContext>
    <local:DataModel />
</Window.DataContext>
 <StackPanel>
     <Button
         Width="100"
         Height="30"
         Content="{Binding Path=Age}" />
     <Button
         Width="100"
         Height="30"
         Content="{Binding MyProperty}" />
 </StackPanel>

DataModel

csharp 复制代码
  public class DataModel : Window
  {
      public int MyProperty { get; set; } = 100;

      // A。依赖属性的定义又叫依赖属性注册。通过DependencyProperty.Register()方法。
      // 方法参数:
      // 1.属性名
      // 2.属性类型
      // 3.依赖属性所属的类
      // 4.属性元数据,依赖属性的默认值
      public static readonly DependencyProperty AgeProperty =
            DependencyProperty.Register("Age", typeof(int), typeof(MainWindow), new PropertyMetadata(18));
      // 包装器:把依赖属性AgeProperty包装一下,可以理解成给依赖属性AgeProperty添加一个"外壳"。
      // 添加"外壳"后让依赖属性用起来和普通属性一个用法。

      // B。依赖属性的包装器:
      public int Age
      {
          get { return (int)GetValue(AgeProperty); }
          set { SetValue(AgeProperty, value); }
      }
  }
相关推荐
2601_9621741720 小时前
Redis 简介
数据库·redis·wpf
SamChan902 天前
Python+PyMuPDF提取PDF表格并翻译:表格结构检测与双语重建实战
windows·python·ai·pdf·wpf
SamChan902 天前
Python+OpenCV检测PDF翻译后排版偏移:像素级格式一致性验证
python·opencv·ai·pdf·wpf
FuckPatience2 天前
WPF 拿到控件的最初样式,修改获得焦点样式
wpf
主宰者2 天前
【WPF】MainWindow前添加加载窗口,发现加载过程中有白色无内容窗口闪烁一下的解决方案
wpf
Vae_Mars3 天前
WPF中的ControlTemplate(控件模板)
wpf
SamChan903 天前
Python+ReportLab自动生成PDF翻译质量审计报告:从数据到可视化的完整方案
开发语言·python·ai·pdf·wpf
circuitsosk3 天前
多智能体协同在能源数据分析中的实践:分配-执行-校验闭环架构设计
python·数据分析·wpf·能源·并行计算·多智能体系统·agent协作
weixin199701080164 天前
《大促护航:电商API限流与降级,双11峰值500万调用的架构复盘》(附Python源码)
python·架构·wpf
hh9505 天前
gent Plan x DeepSeek Harness:多 Agent 协作场景下的中央编排实践
人工智能·wpf·adg·火山引擎·agent plan·adg成都社区