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 分钟前
【经典书籍】《编写可读代码的艺术》精华
开发语言·c++·软件工程·团队开发
空空kkk3 分钟前
Java——接口
java·开发语言·python
MaxHua6 分钟前
JAVA开发处理金额的数据类型你知道多少?
java·后端
oak隔壁找我14 分钟前
公司级 Maven Parent POM 设计指南
java·后端
zl97989927 分钟前
SpringBoot-Web开发之内容协商
java·spring boot
bb456b28 分钟前
Snipaste (截图贴图工具) 精准截图 中文免费版
java·工具·贴图
夜晚中的人海39 分钟前
【C++】二分查找算法习题
开发语言·c++·算法
SimonKing1 小时前
【开发者必备】Spring Boot 2.7.x:WebMvcConfigurer配置手册来了(三)!
java·后端·程序员
2301_801252221 小时前
前端框架Vue(Vue 的挂载点与 data 数据对象)
java·前端·javascript·vue.js·前端框架