我使用this SO post(Ray Burn的答案)中提供的技术将我的RichTextBox
绑定到我的视图模型(VM)的基础string
- 类型属性。我面临的问题是,即使在焦点更改后,当用户在RichTextBox
中输入内容时,基础字段似乎也不会更新。以下是相关的XAML(SyntaxHighlighterTextBox
是一个继承自RichTextBox
的自定义控件):
<local:SyntaxHighlighterTextBox
local:RichTextBoxHelper.DocumentXaml="{Binding Query, UpdateSourceTrigger=PropertyChanged}" />
以下是基础VM的Query
属性:
Public Property Query() As String
Get
Return mQuery
End Get
Set(ByVal value As String)
mQuery = value
RaiseEvent PropertyChanged(Me, New System.ComponentModel.PropertyChangedEventArgs("Query"))
End Set
End Property
这是我的处理程序代码:
Public Shared Sub MyHandler(obj As DependencyObject, e As DependencyPropertyChangedEventArgs)
Dim rtb = DirectCast(obj, SyntaxHighlighterTextBox)
Dim xaml = GetDocumentXaml(rtb)
Dim doc = New FlowDocument()
range = New TextRange(doc.ContentStart, doc.ContentEnd)
range.Load(New MemoryStream(Encoding.UTF8.GetBytes(xaml)), DataFormats.Text)
rtb.Document = doc
AddHandler range.Changed, Sub(obj2, e2)
If rtb.Document Is doc Then
Dim buffer As New MemoryStream()
range.Save(buffer, DataFormats.Text)
SetDocumentXaml(rtb, Encoding.UTF8.GetString(buffer.ToArray()))
End If
End Sub
End Sub