C# WPF依赖属性-数据绑定不';行不通

C# WPF依赖属性-数据绑定不';行不通,c#,wpf,data-binding,dependency-properties,C#,Wpf,Data Binding,Dependency Properties,正如标题所说,我在使用DependencyProperty的数据绑定时遇到了问题。我有一个叫做HTMLBox的类: public class HTMLBox : RichTextBox { public static readonly DependencyProperty TextProperty = DependencyProperty.Register("Text", typeof(string), typeof(HTMLBox)); public string

正如标题所说,我在使用DependencyProperty的数据绑定时遇到了问题。我有一个叫做HTMLBox的类:

public class HTMLBox : RichTextBox
{
    public static readonly DependencyProperty TextProperty = 
    DependencyProperty.Register("Text", typeof(string), typeof(HTMLBox));

    public string Text
    {
        get
        {
            return GetValue(TextProperty) as string;
        }
        set
        {
            Console.WriteLine("Setter...");
            SetValue(TextProperty, value);
        }
    }

    public HTMLBox()
    {
        // Create a FlowDocument
        FlowDocument mcFlowDoc = new FlowDocument();

        // Create a paragraph with text
        Paragraph para = new Paragraph();
        para.Inlines.Add(new Bold(new Run(Text)));

        // Add the paragraph to blocks of paragraph
        mcFlowDoc.Blocks.Add(para);

        this.Document = mcFlowDoc;
    }
}
我正在读取构造函数中的Text属性,因此当字符串绑定到该属性时,它应该显示为文本。但是,即使我将一些数据绑定到xaml中的Text属性,我甚至看不到“Setter…”消息,设置Text属性时应该显示该消息

    <local:HTMLBox Text="{Binding Text}" 
           Width="{Binding Width}"  
           AcceptsReturn="True" 
           Height="{Binding Height}" />


如果我将HTMLBox更改为TextBox,文本将正确显示,因此错误可能在HTMLBox类中的某个位置。我做错了什么?

这里有一些问题:

  • 您不应该在CLR属性的集合/获取中放置逻辑,该集合/获取封装了依赖项属性。此属性仅用于提供更方便的机制来获取/设置依赖项属性。不能保证XAML解析器将调用此setter。如果在更改依赖项属性时需要调用任何逻辑,请在通过
    dependencProperty.register
    注册依赖项属性时,通过更改事件处理程序执行此操作
  • 在构造函数中构建控件的UI时,这里会出现计时问题!要构造类的实例,首先调用构造函数,然后设置各种属性<代码>文本将始终是构造函数中的默认值。同样,与(1)类似的解决方案是,当
    Text
    属性发生更改时,重建/更新UI

  • 谢谢,使用更改事件处理程序解决了这个问题。似乎我在这里有很多东西要学:)