ビューモデルのプロパティにバインドされた添付プロパティを使用してフォーカスを設定している TextBox があります。添付プロパティは「UIElement.Focus()」を呼び出してフォーカスを設定します。問題は、TextBox がこの方法でフォーカスを受け取ると、"GotFocus" イベントが発生しないことです。イベントを処理するために Caliburn.Micro の Message.Attach を使用しています。何か案は?
ここにテキストボックスがあります。
<TextBox x:Name="Test"
Grid.Column="0"
Text="{Binding Test, Converter={StaticResource TestToStringConverter}}"
AttachedProperties:FocusExtension.IsFocused="{Binding IsTestFocused}"
cal:Message.Attach="[Event GotFocus] = [Action OnGotFocus($eventargs)]; />
これが添付プロパティです(SOにあります)。
public static class FocusExtension
{
public static bool GetIsFocused(DependencyObject obj)
{
return (bool) obj.GetValue(IsFocusedProperty);
}
public static void SetIsFocused(DependencyObject obj, bool value)
{
obj.SetValue(IsFocusedProperty, value);
}
public static readonly DependencyProperty IsFocusedProperty =
DependencyProperty.RegisterAttached("IsFocused", typeof (bool), typeof (FocusExtension),
new UIPropertyMetadata(false, OnIsFocusedPropertyChanged));
private static void OnIsFocusedPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var uie = (UIElement)d;
if ((bool)e.NewValue)
{
uie.Focus();
}
}
}