【发布时间】:2020-05-03 18:04:26
【问题描述】:
我有 1 个自定义控件需要将数据绑定到 2 个不同的用户控件:
<TextBlock
Text="{Binding Title}">
</TextBlock>
<RichTextBox
x:Name="RichTextBoxControl"
Focusable="False"
Document="{Binding UserLogs}">
</RichTextBox>
他们试图绑定的属性在同一个 DataContext 中,并且定义如下:
public string Title {
get => return _title;
set {
_title = value;
NotifyPropertyChanged();
}
}
private string _title;
public FlowDocument UserLogs {
get => return _userlogs;
set {
_userlogs = value;
NotifyPropertyChanged();
}
}
private FlowDocument _userlogs;
TextBlock 的绑定问题为 0(无论是在编译时,还是在运行时)。
虽然对于 RichTextBox 的绑定,我在 Visual Studio 的分析器中遇到错误(在运行时在我的 UserControl 的 InitializeComponent() 中):“Impossible to define 'Binding' on the 'Document' property of type 'RichTextBox'. A binding can only be defined on a DependencyProperty of a DependencyObject”
所以我非常清楚如何使用 DependencyProperty 技巧来修复该错误,但我真的不明白这两个绑定之间有什么区别以及为什么我必须在第二个绑定中使用 DependencyProperty 而第一个绑定没有它就像一个魅力。
我有点想在不了解背后原因的情况下解决这个问题,这对我来说是迈向无法理解的黑色巫术的一步 T.T
欢迎任何解释:)
【问题讨论】:
-
A binding can only be defined on a DependencyProperty of a DependencyObject因为Document不是DependencyProperty这就是为什么...Text是一个dep obj。对于TextBox以及它为什么起作用。 -
哦,所以它可能也取决于您绑定的属性...不知道:/我虽然可以绑定任何我可以在后面的代码中修改的属性而没有任何麻烦跨度>
-
不,你只能绑定到
DependencyProperty... -
为了增加精度,您只能绑定一个依赖属性,但您可以绑定任何属性。前者是Binding的目标,后者是源。
-
您也可以在
RichTextBox中添加FlowDocument,然后您可以绑定到Run.Text。例如<FlowDocument> <Paragraph> <Run Text="{Binding something}"/> </Paragraph> </FlowDocument>
标签: c# wpf xaml data-binding richtextbox