You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

如何创建可将属性与控件属性绑定的对象?

如何创建可将属性与控件属性绑定的对象?

嗨,看你已经开始基于DependencyObject创建类并注册DependencyProperty了,这可是实现WPF属性绑定的核心基础!不过要让这个对象的属性能和控件属性顺畅绑定,还有几个关键细节要完善,我一步步给你说:

首先,先把你的类补全——依赖属性需要对应的CLR包装器,这样我们平时写代码访问属性时更方便,WPF底层还是会走依赖属性的逻辑:

public class DependencyPair : DependencyObject
{
    public static readonly DependencyProperty Object1Property =
        DependencyProperty.Register("Object1", typeof(object), typeof(DependencyPair));

    public static readonly DependencyProperty Object2Property =
        DependencyProperty.Register("Object2", typeof(object), typeof(DependencyPair));

    // CLR属性包装器,必须严格按GetValue/SetValue来写,不能加额外逻辑(除非用回调)
    public object Object1
    {
        get => GetValue(Object1Property);
        set => SetValue(Object1Property, value);
    }

    public object Object2
    {
        get => GetValue(Object2Property);
        set => SetValue(Object2Property, value);
    }
}

接下来,说说怎么把这个对象和控件绑定:

  • 在XAML里作为数据源绑定:你可以把DependencyPair实例放到资源中,然后让控件的属性绑定到它的属性上。比如:
<!-- 先在窗口资源中创建实例 -->
<Window.Resources>
    <local:DependencyPair x:Key="MyPair" Object1="默认文本1" Object2="默认文本2"/>
</Window.Resources>

<!-- 绑定两个TextBox的Text属性 -->
<TextBox Text="{Binding Source={StaticResource MyPair}, Path=Object1}" Margin="5"/>
<TextBox Text="{Binding Source={StaticResource MyPair}, Path=Object2}" Margin="5"/>
  • 开启双向绑定(可选但常用):如果希望控件修改内容后,自动同步回DependencyPair的属性,注册依赖属性时要加上FrameworkPropertyMetadata,设置双向绑定默认开启:
public static readonly DependencyProperty Object1Property =
    DependencyProperty.Register(
        "Object1", 
        typeof(object), 
        typeof(DependencyPair),
        new FrameworkPropertyMetadata(
            null, 
            FrameworkPropertyMetadataOptions.BindsTwoWayByDefault));
  • 属性变更回调(按需添加):要是你想在属性值变化时执行一些自定义逻辑,比如同步其他属性或者触发通知,可以在注册时添加回调方法:
public static readonly DependencyProperty Object1Property =
    DependencyProperty.Register(
        "Object1", 
        typeof(object), 
        typeof(DependencyPair),
        new FrameworkPropertyMetadata(
            null, 
            FrameworkPropertyMetadataOptions.BindsTwoWayByDefault,
            OnObject1PropertyChanged));

private static void OnObject1PropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
    var pair = (DependencyPair)d;
    // 这里写属性变化后的逻辑,比如打印日志、更新Object2等
    Console.WriteLine($"Object1从{e.OldValue}变成了{e.NewValue}");
}

这样一来,你的DependencyPair对象就能完美和控件属性绑定啦!

备注:内容来源于stack exchange,提问作者Hürol Aslan

火山引擎 最新活动