SilverlightではUpdateSourceTriggerが使えない。でも使いたい。検索してみると、Forumにそれを実現するコードがあるので書いてみました。
Binding.UpdateSourceTrigger : The Official Microsoft Silverlight Site
VB.NETに変換して……。
Public Class UpdateSourceTriggerHelper
Public Shared ReadOnly UpdateSourceTriggerProperty As DependencyProperty = _
DependencyProperty.RegisterAttached("UpdateSourceTrigger", GetType(Boolean), GetType(UpdateSourceTriggerHelper), New PropertyMetadata(AddressOf OnUpdateSourceTriggerChanged))
Public Shared Function GetUpdateSourceTrigger(ByVal d As DependencyObject) As Boolean
Return CBool(d.GetValue(UpdateSourceTriggerProperty))
End Function
Public Shared Sub SetUpdateSourceTrigger(ByVal d As DependencyObject, ByVal value As Boolean)
d.SetValue(UpdateSourceTriggerProperty, value)
End Sub
Private Shared _textBox As TextBox
Private Shared Sub OnUpdateSourceTriggerChanged(ByVal d As DependencyObject, ByVal e As DependencyPropertyChangedEventArgs)
If Not TypeOf d Is TextBox Then
Exit Sub
End If
_textBox = DirectCast(d, TextBox)
If CBool(e.OldValue) Then
RemoveHandler _textBox.TextChanged, AddressOf TextBox_TextChanged
End If
If CBool(e.NewValue) Then
AddHandler _textBox.TextChanged, AddressOf TextBox_TextChanged
End If
End Sub
Private Shared Sub TextBox_TextChanged(ByVal sender As Object, ByVal e As EventArgs)
Dim c = FindFocusableControl(_textBox)
If c IsNot Nothing Then
c.Focus()
End If
_textBox.Focus()
End Sub
Private Shared Function FindFocusableControl(ByVal control As Control) As Control
Dim ctl = VisualTreeHelper.GetParent(control)
If TypeOf ctl Is Control Then
Return DirectCast(ctl, Control)
Else
Dim childrenCount = VisualTreeHelper.GetChildrenCount(ctl)
For i = 0 To childrenCount - 1
Dim c = TryCast(VisualTreeHelper.GetChild(ctl, i), Control)
If c IsNot Nothing AndAlso Not c Is control Then
Return c
End If
Next
End If
Return Nothing
End Function
End Class
XAMLはこんな感じ。
<TextBox Text="{Binding Hoge, Mode=TwoWay}"
local:UpdateSourceTriggerHelper.UpdateSourceTrigger="True" />
処理内容は、TextChangedイベントが発生したらまわりのコントロールを探して、一度フォーカスを別のコントロールに変えて、またTextBoxに戻すというもの。これでUpdateSourceTriggerみたいに振舞うようにするってことですね。
実際にうごかしてみると、フォーカスが移動しているということは見た目状わかりませんが、だーーーーめがっさ英語圏的な実装じゃないかこれ。入力中にフォーカス移動させたら日本語打てないじゃん……。難しいなあ。