附加属性的多次使用不起作用
我的猜测是我没有正确理解附加属性。我正在尝试将 RichTextBox 上的 FlowDocument 转换为视图模型中的 HTML 字符串属性。我有两个使用我的 RichTextBoxAssistant
类的 RichTextBox(感谢 这篇博文):
<RichTextBox x:Name="rtb_description"
local:RichTextBoxAssistant.BoundDocument="{Binding MyVM.Description,
ValidatesOnDataErrors=True}"/>
<RichTextBox x:Name="rtb_descriptionHowTo"
local:RichTextBoxAssistant.BoundDocument="{Binding MyVM.DescriptionHowTo,
ValidatesOnDataErrors=True}" />
在我的 RichTextBoxAssistant
类中,我有这个依赖属性:
public static readonly DependencyProperty BoundDocument =
DependencyProperty.RegisterAttached(
"BoundDocument",
typeof(string),
typeof(RichTextBoxAssistant),
new FrameworkPropertyMetadata(
null,
FrameworkPropertyMetadataOptions.BindsTwoWayByDefault,
boundDocumentChanged
)
);
问题是 boundDocumentChanged
方法当我更改第一个 RichTextBox rtb_description
中的值时会受到影响,但当我更改 rtb_descriptionHowTo
中的值时不会受到影响。当我更改文本或对 rtb_descriptionHowTo
执行任何操作时,我永远不会达到 boundDocumentChanged
。这是 RichTextBoxAssistant
是静态类的结果吗?如何修复它以便我可以将 RichTextBoxAssistant
与多个 RichTextBox 一起使用?
My guess is I'm not understanding attached properties correctly. I'm trying to convert the FlowDocument on a RichTextBox to an HTML string property in my view model. I have two RichTextBoxes that are using my RichTextBoxAssistant
class (thanks to this blog post):
<RichTextBox x:Name="rtb_description"
local:RichTextBoxAssistant.BoundDocument="{Binding MyVM.Description,
ValidatesOnDataErrors=True}"/>
<RichTextBox x:Name="rtb_descriptionHowTo"
local:RichTextBoxAssistant.BoundDocument="{Binding MyVM.DescriptionHowTo,
ValidatesOnDataErrors=True}" />
In my RichTextBoxAssistant
class, I have this dependency property:
public static readonly DependencyProperty BoundDocument =
DependencyProperty.RegisterAttached(
"BoundDocument",
typeof(string),
typeof(RichTextBoxAssistant),
new FrameworkPropertyMetadata(
null,
FrameworkPropertyMetadataOptions.BindsTwoWayByDefault,
boundDocumentChanged
)
);
The problem is that the boundDocumentChanged
method gets hit when I change the value in my first RichTextBox, rtb_description
, but not when I change the value in rtb_descriptionHowTo
. When I change the text or do anything to rtb_descriptionHowTo
, I never reach boundDocumentChanged
. Is this a result of RichTextBoxAssistant
being a static class? How can I fix it so that I can use RichTextBoxAssistant
with multiple RichTextBoxes?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
ColinE 的想法是正确的:我尝试从第一个 RichTextBox 中删除附加属性,并仍然更改第二个 RichTextBox 的值没有将我置于
boundDocumentChanged
中。结果我的视图模型中的DescriptionHowTo
属性为 null,而不是 HTML 字符串。当我将其初始化为@""
时,一切开始工作。ColinE had the right idea: I tried removing the attached property from my first RichTextBox, and changing the value of the second RichTextBox still didn't put me in
boundDocumentChanged
. Turns out myDescriptionHowTo
property in my view model was null, instead of an HTML string. When I initialized it to@"<html><body></body></html>"
, things started working.