WPF XAML中使用依赖属性

自定义的控件MyCustomControl,它有一个依赖属性MyProperty。首先,我们需要在控件的代码文件中创建这个依赖属性:

复制代码
public class MyCustomControl : Control
{
    public static readonly DependencyProperty MyPropertyProperty =
        DependencyProperty.Register("MyProperty", typeof(string), typeof(MyCustomControl), new PropertyMetadata(default(string)));
    public string MyProperty
    {
        get { return (string)GetValue(MyPropertyProperty); }
        set { SetValue(MyPropertyProperty, value); }
    }
}

在XAML文件中使用这个控件及其依赖属性:

复制代码
<Window x:Class="WpfApp.MainWindow"
        xmlns="<http://schemas.microsoft.com/winfx/2006/xaml/presentation>"
        xmlns:x="<http://schemas.microsoft.com/winfx/2006/xaml>"
        xmlns:local="clr-namespace:WpfApp"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <local:MyCustomControl MyProperty="这是一个测试字符串" />
    </Grid>
</Window>

在这个例子中,local 是XAML文件中定义的XML命名空间前缀,clr-namespace:WpfApp 指定了 MyCustomControl 定义所在的命名空间。MyProperty 是在 MyCustomControl 中定义的依赖属性,我们可以在XAML中直接设置它的值。

相关推荐
人活一口气1 小时前
Spring Boot与AIGC的完美结合:从零搭建智能内容生成平台
java·spring boot·aigc
像我这样帅的人丶你还3 小时前
Java 后端详解(三):全局异常处理与 JPA 数据库映射
java·后端
NE_STOP4 小时前
vibe Coding -- 小项目实战
java
未秃头的程序猿9 小时前
Java 26正式发布!这3个新特性,让代码量直接减半
java·后端·面试
用户2986985301410 小时前
Word 文档文本查找与替换的 Java 实现方案
java·后端
阿哉10 小时前
Nacos 服务发现源码:藏在背后的两套事件机制,90%的人只讲了一半
java
咖啡八杯10 小时前
GoF设计模式——命令模式
java·设计模式·架构
AI人工智能_电脑小能手10 小时前
【大白话说Java面试题 第125题】【并发篇】第25题:说说 Java 线程的中断机制
java·后端·面试
Java内核笔记10 小时前
Spring Security 源码解析(六)无状态 JWT 实践:Session 共享与自定义过滤器
java·后端
荣码10 小时前
LangGraph多Agent协作:3个Agent干活比1个强,但我踩了4个坑
java·python