[英]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中的Text属性,我甚至看不到“Setter ...” - 应该在设置Text-property时显示的消息。
<local:HTMLBox Text="{Binding Text}"
Width="{Binding Width}"
AcceptsReturn="True"
Height="{Binding Height}" />
如果我将HTMLBox更改为TextBox,则文本显示正确,因此错误可能是我的HTMLBox类中的错误。 我究竟做错了什么?
你有几个问题在这里:
DependencyProperty.Register
注册依赖项属性时通过更改事件处理程序执行此操作。 Text
将始终是构造函数中的默认值。 同样,对于(1)的类似解决方案,当Text
属性更改时,重建/更新UI。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.