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 小时前
Java学习第22天 - 云原生与容器化
java
渣哥3 小时前
原来 Java 里线程安全集合有这么多种
java
间彧3 小时前
Spring Boot集成Spring Security完整指南
java
间彧3 小时前
Spring Secutiy基本原理及工作流程
java
Java水解4 小时前
JAVA经典面试题附答案(持续更新版)
java·后端·面试
洛小豆6 小时前
在Java中,Integer.parseInt和Integer.valueOf有什么区别
java·后端·面试
前端小张同学7 小时前
服务器上如何搭建jenkins 服务CI/CD😎😎
java·后端
ytadpole7 小时前
Spring Cloud Gateway:一次不规范 URL 引发的路由转发404问题排查
java·后端
华仔啊7 小时前
基于 RuoYi-Vue 轻松实现单用户登录功能,亲测有效
java·vue.js·后端