我有一个 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();
}
}
}