1

I have MyContainer User Control with Grid inside. Each cell of this Grid contains a some control derived from MyControlBase class. These controls are added dynamically.

I need to implement a FocusedControl bound property in MyContainer to get currently focused or set focus to any of MyControlBase children. I know about FocusManager.FocusedElement but haven't ideas how to implement it properly.

asktomsk
  • 2,289
  • 16
  • 23

2 Answers2

0

Dunno if this helps your situation, or if it's even the right way to go about mine, but in a pinch I've found that listening for the Loaded event on the object I want to focus and then using Dispatcher.BeginInvoke to send a Focus request to my control on the Background or ApplicationIdle priority has worked when other methods haven't. For example:

private void MyControlLoaded(object sender, RoutedEventArgs e)
{
    Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.ApplicationIdle, new Action( () => MyControl.Focus() ));
}
Charles Josephs
  • 1,495
  • 3
  • 14
  • 25
  • Thanks, I know how to make any element focused :) I need a pretty set/get property to control it dynamically to binding in other controls. – asktomsk Mar 21 '12 at 14:15
0

OK, I found how to do it myself.

First define our new dependence property FocusedAdapterProperty as usual:

    public static readonly DependencyProperty FocusedAdapterProperty;

    static SpreadGridControl()
    {
        FocusedAdapterProperty = DependencyProperty.Register("FocusedAdapter",
                            typeof(object), typeof(SpreadGridControl),
                            new FrameworkPropertyMetadata(null, null));
    }

    public object FocusedAdapter
    {
        get { return GetValue(FocusedAdapterProperty); }
        set { SetValue(FocusedAdapterProperty, value); }
    }

Next add GotFocus handler to parent container e.g. <Grid GotFocus="Grid_OnGotFocus">
Check the e.OriginalSource and search most common ancestor of required type and set property to new value:

    private void Grid_OnGotFocus(object sender, RoutedEventArgs e)
    {
        var control = UIHelpers.TryFindParent<ControlBase>
            ((DependencyObject)e.OriginalSource);
        if (control != null)
            FocusedAdapter = control.Adapter;
    }

The implementation of TryFindParent can be found here

Community
  • 1
  • 1
asktomsk
  • 2,289
  • 16
  • 23