0

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

1 回答 1

0

我自己试过这个,并且能够复制这个问题。我不太确定为什么会发生这种情况,它可能与用户控件(即视图)的生命周期有关。一种选择可能是扩展您的附加属性,以便它在调用uie.Focus().

动词的名称可以是附加属性的依赖属性FocusExtension,并且可以在视图中设置。

于 2011-03-21T23:02:33.627 回答