値を要求する前に、フォーカスを他の要素に明示的に設定することで、これを解決しました。これは明らかに、現在フォーカスを持っている要素を失い、バインディングを更新します。
焦点を設定するために、他の質問に対する回答に触発されて、添付プロパティを作成しました。また、私の他の質問と一緒に、これを多少自動化しました。
したがって、それを使用するには、基本的にプロパティを要素 (この場合はタブ コントロール) にアタッチします。
<TabControl c:Util.ShouldFocus="{Binding ShouldClearFocus}">
私のビューモデルには、 を発生さShouldClearFocus
せる標準プロパティである単純なブール値プロパティがあるPropertyChangedEvent
ため、データバインディングが機能します。次に、フォーカスをリセットしたいときに設定ShouldClearFocus
するだけです。true
添付プロパティは自動的にフォーカスを設定し、プロパティ値を再度リセットします。ShouldClearFocus
そうすれば、その間に設定する必要なく設定を続けることができますfalse
。
添付プロパティは、これを変更ハンドラーとして使用する標準実装です。
public static void ShouldFocusChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e)
{
if (!(bool)e.NewValue || !(obj is FrameworkElement))
return;
FrameworkElement element = (FrameworkElement)obj;
if (element.Focusable)
element.Focus();
// reset value
BindingExpression bindingExpression = BindingOperations.GetBindingExpression(obj, ShouldFocusProperty);
if (bindingExpression != null)
{
PropertyInfo property = bindingExpression.DataItem.GetType().GetProperty(bindingExpression.ParentBinding.Path.Path);
if (property != null)
property.SetValue(bindingExpression.DataItem, false, null);
}
else
SetShouldFocus(obj, false);
}