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中直接设置它的值。

相关推荐
深念Y2 分钟前
为什么选 Go:直观、可维护、AI 友好
linux·开发语言·人工智能·golang·agent·harness
Billy1213810 分钟前
Day25-编译期计算与 constexpr if:跨越编译与运行的边界
开发语言·c++进阶学习
xbgRS23 分钟前
RocketMQ中的broker
java·rocketmq
小小龙学IT27 分钟前
第七节 C++ 与 QML 交互
开发语言·qt
晓晓_za89866843 分钟前
Geo 优化源码二次开发:自定义地域规则改造实操文档
java·开发语言·搜索引擎·ci/cd·矩阵
摇滚侠43 分钟前
《SpringBoot 3:入门与应用实战》第 8 章 AOP 的进阶机制和应用 阅读笔记 16
java·spring boot·笔记
AI人工智能+电脑小能手1 小时前
大白话说Java设计模式-38-迭代器模式(业务实战篇)
java·设计模式·迭代器模式·stream·遍历封装·集合通用·分页遍历
QQ_21696290961 小时前
【源码编号:project86570】SpringBoot电影院在线选座售票系统:电影排片、在线选座、订单购票、后台管理完整实战
java·spring boot·后端
ShineWinsu1 小时前
对于TRAE中配置Qt的解析
开发语言·c++·ide·vscode·qt·ai·trae
谢亮_vipxieliang1 小时前
手机号验证技术方案:号段规则与正则表达式
java·服务器·spring boot·正则表达式·hibernate