开发者

WPF Dependency Property -Databinding doesn't work

开发者 https://www.devze.com 2023-03-27 05:40 出处:网络
As the title already says I am having trouble using databinding with a DependencyProperty. I have a class called HTMLBox:

As the title already says I am having trouble using databinding with a DependencyProperty. I have a class called 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;
    }
}

I reading the Text-property in the Constructor, so it should be displayed as text when a string is bound to the property. But even though I bind some data to the Text property in xaml, I don't even see the "Setter..."-Message which should b开发者_Go百科e shown when the Text-property is set.

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

If I change HTMLBox to TextBox the text is displayed properly, so the mistake is probably somwhere in my HTMLBox class. What am I doing wrong?


You have a few issues going on here:

  1. You should not place logic in the set / get of your CLR property which wraps your dependency property. This property is only there to provide a more convenient mechanism for getting / setting your dependency property. There is no guarantee that the XAML parser will invoke this setter. If you need to invoke any logic when your dependency property is changed, do this via a change event handler when you register your dependency property via DependencyProperty.Register.
  2. You build your control's UI in the constructor, you have timing issue here! To construct an instance of your class the constructor is first called, then the various properties are set. Text will always be the default value in the constructor. Again, a similar solution to (1), when your Text property changes, rebuild / update your UI.
0

精彩评论

暂无评论...
验证码 换一张
取 消