WPF 依赖属性 - 数据绑定不起作用
正如标题所示,我在使用具有 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 属性,我什至没有看到设置 Text 属性时应显示的“Setter...”消息。
<local:HTMLBox Text="{Binding Text}"
Width="{Binding Width}"
AcceptsReturn="True"
Height="{Binding Height}" />
如果我将 HTMLBox 更改为 TextBox,文本将正确显示,因此错误可能出在我的 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 be 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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这里存在一些问题:
Text
将始终是构造函数中的默认值。再次,与 (1) 类似的解决方案,当您的Text
属性更改时,重建/更新您的 UI。You have a few issues going on here:
DependencyProperty.Register
.Text
will always be the default value in the constructor. Again, a similar solution to (1), when yourText
property changes, rebuild / update your UI.