[英]WPF Dependency Property -Databinding doesn't work
As the title already says I am having trouble using databinding with a DependencyProperty. 正如标题所说,我在使用DependencyProperty进行数据绑定时遇到问题。 I have a class called HTMLBox:
我有一个名为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. 我在构造函数中读取Text属性,因此当字符串绑定到属性时,它应显示为文本。 But even though I bind some data to the Text property in xaml, I don't even see the "Setter..."-Message which should be shown when the Text-property is set.
但即使我将一些数据绑定到xaml中的Text属性,我甚至看不到“Setter ...” - 应该在设置Text-property时显示的消息。
<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. 如果我将HTMLBox更改为TextBox,则文本显示正确,因此错误可能是我的HTMLBox类中的错误。 What am I doing wrong?
我究竟做错了什么?
You have a few issues going on here: 你有几个问题在这里:
DependencyProperty.Register
. DependencyProperty.Register
注册依赖项属性时通过更改事件处理程序执行此操作。 Text
will always be the default value in the constructor. Text
将始终是构造函数中的默认值。 Again, a similar solution to (1), when your Text
property changes, rebuild / update your UI. Text
属性更改时,重建/更新UI。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.