繁体   English   中英

WPF依赖项属性-Databinding不起作用

[英]WPF Dependency Property -Databinding doesn't work

正如标题所说,我在使用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中的T​​ext属性,我甚至看不到“Setter ...” - 应该在设置Text-property时显示的消息。

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

如果我将HTMLBox更改为TextBox,则文本显示正确,因此错误可能是我的HTMLBox类中的错误。 我究竟做错了什么?

你有几个问题在这里:

  1. 您不应该将逻辑放在包装依赖项属性的CLR属性的set / get中。 此属性仅用于提供更方便的获取/设置依赖项属性的机制。 无法保证XAML解析器将调用此setter。 如果需要在更改依赖项属性时调用任何逻辑,请在通过DependencyProperty.Register注册依赖项属性时通过更改事件处理程序执行此操作。
  2. 你在构造函数中构建控件的UI,这里有时间问题! 要构造类的实例,首先调用构造函数,然后设置各种属性。 Text将始终是构造函数中的默认值。 同样,对于(1)的类似解决方案,当Text属性更改时,重建/更新UI。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM