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

相关推荐
智感子13 分钟前
智能称重·数据上云:从仪表读数到可追溯的计量凭证
开发语言·php
\光辉岁月/22 分钟前
7.javase-面向对象
java·开发语言
weixin_5310946937 分钟前
heap_4内存管理
java·开发语言·算法
疯狂的维修43 分钟前
关于用C#写电机起保停控制
开发语言·c#
程序员南飞44 分钟前
win系统安装minio
java·数据结构·算法
Escalating_xu1 小时前
【Python】使用库:标准库、第三方库、pip、项目实战与程序打包
java·python·pip
Wang's Blog2 小时前
Java框架 SpringCloud 快速入门: 过滤器链执行顺序
java·spring cloud
geovindu2 小时前
rust: Abstract Factory pattern
开发语言·后端·设计模式·rust·抽象工厂模式
砚底藏山河2 小时前
量化实战:回测数据底座快照与版本管理进阶
java·大数据·python·金融·maven
“AI国潮设计-小江”2 小时前
《Python+SDXL实战:用ControlNet批量生成“英歌舞麻将糕”IP,附自动化脚本与商用思路》
开发语言·人工智能·python·prompt·aigc