WPF -Databinding dependency property not working

As mentioned in the header, I am having problems using data binding using 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 am reading a text property in the constructor, so it should appear as text when the string is bound to the property. But even if I bind some data to the Text property in xaml, I don’t even see "Setter ..." - Message, which should be displayed when the Text property is set.

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

If I change the HTMLBox in the TextBox, the text displays correctly, so the error is probably in my HTMLBox class. What am I doing wrong?

+4
source share
1 answer

You have a few problems here:

  • You should not place logic in the set / get of a CLR property that wraps your dependency property. This property is only available 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 call any logic when changing a dependency property, do this using the change event handler when you register your dependency property through DependencyProperty.Register .
  • You create your user management interface in the constructor, you have the timing here! To build an instance of your class, the constructor is called first, then various properties are set. Text will always be the default value in the constructor. Again, a similar solution (1), when the Text property is changed, rebuilds / updates your interface.
+4
source

All Articles