views:

89

answers:

1

Hi guys, I'm trying to bind focus for my control to a property on the view model, like this:

 public class Focus
{
    public static readonly DependencyProperty HasFocusProperty = DependencyProperty.RegisterAttached("HasFocus",
                                                                                                             typeof(bool),
                                                                                                             typeof(Focus),
                                                                                                             new PropertyMetadata(false, HandleHasFocusChanged),
                                                                                                             null
                                                                                                            );

    private static void HandleHasFocusChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        var uiElement = d as UIElement;
        var value = (bool)e.NewValue;

        if (value)
        {
            FocusManager.SetFocusedElement(uiElement, uiElement);
        }
    }

    public static bool GetHasFocus(UIElement obj)
    {
        return (bool)obj.GetValue(HasFocusProperty);
    }

    public static void SetHasFocus(UIElement obj, bool value)
    {
        obj.SetValue(HasFocusProperty, value);
    }
}

This works for the first focus, but then after that it seems to not have any affect at all

Anybody know what I'm doing wrong, or even a better way to do what I'm trying to achieve?

+1  A: 

Probably the difference between logical focus and keyboardfocus is biting you. You can read about it here. Pay particular attention to the part about focus scope. You have implemented code to set the logical focus to your user control when the HasFocus property is set to true, but you do nothing when it is set to false. In that case the logical focus will stay where it is. On the other hand, you have not hooked up an event handler for the user control's lostfocus event. That means that your HasFocus property will once more be unaffected when the control loses focus.

Dabblernl
I don't need to make it lose focus yet, i'll implement that later. I removed the LostFocus event handling to simpify my code. I'll look in to the focus scope thing, thanks
Michael Baldry
Great, I understand wpf focus now.. I do wonder why they've done this though? What was wrong with the old focus system?
Michael Baldry