通过数据绑定在 UserControl 中设置自定义属性 [英] Setting Custom Properties in UserControl via DataBinding

查看:31
本文介绍了通过数据绑定在 UserControl 中设置自定义属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个非常简单的 UserControl——出于所有意图和目的——只不过是 TextBox:

Say I have a very simple UserControl that - for all intents and purposes - is nothing more than TextBox:

public partial class FooBox : UserControl
{
    public static readonly DependencyProperty FooTextProperty =
        DependencyProperty.Register("FooText", typeof(string), typeof(FooBox));

    public FooBox()
    {
        InitializeComponent();
    }

    public string FooText
    {
        get { return textBlock.Text; }
        set { textBlock.Text = value; }
    }
}

<UserControl x:Class="Namespace.FooBox"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Height="300" Width="300">
    <Grid>
        <TextBlock x:Name="textBlock" />
    </Grid>
</UserControl>

在表单上声明为:

<local:FooBox FooText="{Binding Name}" />

表单的 DataContext 设置为具有 Name 属性的对象.但这对我不起作用.我错过了什么?

The form's DataContext is set to an object that has a Name property. But this is not working for me. What am I missing?

推荐答案

事实证明真正的问题是我期望 WPF 框架设置我的公共属性,然后我的代码将响应更改并根据新值呈现.不是这样.WPF 所做的是直接调用 SetValue() 并完全绕过公共属性.我必须做的是使用 DependencyPropertyDescriptor.AddValueChanged 接收属性更改通知并对此做出响应.它看起来像(在 ctor 内部):

Turns out the real problem is I was expecting the WPF framework to set my public property whereupon my code would respond to the changes and render according to the new value. Not so. What WPF does is call SetValue() directly and completely circumvents the public property. What I had to do was receive property change notifications using DependencyPropertyDescriptor.AddValueChanged and respond to that. It looks something like (inside the ctor):

var dpd = DependencyPropertyDescriptor
    .FromProperty(MyDependencyProperty, typeof(MyClass));
dpd.AddValueChanged(this, (sender, args) =>
{
    // Do my updating.
});

这篇关于通过数据绑定在 UserControl 中设置自定义属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆