简体   繁体   中英

WPF-MVVM: Setting UI control focus from ViewModel

What is a good practice of setting control focus in MVVM architecture.

The way I envision it, is with a property on the ViewModel that would trigger a focus change when needed. And than have the UI controls bind/listen to that property so that if it changes, appropriate focus will be set.

I see it as a ViewModel thing, because i want to set focus appropriate after a certain action was performed by the ViewModel, such as loading certain data.

What's the best practice?

Use the IsFocused Attached Property as suggested in the Answer here: Set focus on textbox in WPF from view model (C#)

Then you can simply bind to a property in your viewmodel.

If you are using Caliburn.Micro, here is a service that I created to set Focus to any Control in the view inherited from Screen.

Note: This will only work if you are using Caliburn.Micro for your MVVM framework.

public static class FocusManager
{
    public static bool SetFocus(this IViewAware screen ,Expression<Func<object>> propertyExpression)
    {
        return SetFocus(screen ,propertyExpression.GetMemberInfo().Name);
    }

    public static bool SetFocus(this IViewAware screen ,string property)
    {
        Contract.Requires(property != null ,"Property cannot be null.");
        var view = screen.GetView() as UserControl;
        if ( view != null )
        {
            var control = FindChild(view ,property);
            bool focus = control != null && control.Focus();
            return focus;
        }
        return false;
    }

    private static FrameworkElement FindChild(UIElement parent ,string childName)
    {
        // Confirm parent and childName are valid. 
        if ( parent == null || string.IsNullOrWhiteSpace(childName) ) return null;

        FrameworkElement foundChild = null;

        int childrenCount = VisualTreeHelper.GetChildrenCount(parent);

        for ( int i = 0; i < childrenCount; i++ )
        {
            FrameworkElement child = VisualTreeHelper.GetChild(parent ,i) as FrameworkElement;
            if ( child != null )
            {

                BindingExpression bindingExpression = GetBindingExpression(child);
                if ( child.Name == childName )
                {
                    foundChild = child;
                    break;
                }
                if ( bindingExpression != null )
                {
                    if ( bindingExpression.ResolvedSourcePropertyName == childName )
                    {
                        foundChild = child;
                        break;
                    }
                }
                foundChild = FindChild(child ,childName);
                if ( foundChild != null )
                {
                    if ( foundChild.Name == childName )
                        break;
                    BindingExpression foundChildBindingExpression = GetBindingExpression(foundChild);
                    if ( foundChildBindingExpression != null &&
                        foundChildBindingExpression.ResolvedSourcePropertyName == childName )
                        break;
                }

            }
        }

        return foundChild;
    }

    private static BindingExpression GetBindingExpression(FrameworkElement control)
    {
        if ( control == null ) return null;

        BindingExpression bindingExpression = null;
        var convention = ConventionManager.GetElementConvention(control.GetType());
        if ( convention != null )
        {
            var bindablePro = convention.GetBindableProperty(control);
            if ( bindablePro != null )
            {
                bindingExpression = control.GetBindingExpression(bindablePro);
            }
        }
        return bindingExpression;
    }
}

How to use this?

From your ViewModel inherited from Caliburn.Micro.Screen or Caliburn.Micro.ViewAware

this.SetFocus(()=>ViewModelProperty); or this.SetFocus("Property");

How it works?

This method will try to search for an element in the Visual Tree of View and focus will be set to any matching control. If no such control found, then it will make use of the BindingConventions used by Caliburn.Micro.

For ex.,

It will look for the Propery in the BindingExpression of the control. For TextBox, it will look whether this property is binded to Text property then the focus will be set.

ViewModel 向 View 抛出一个事件,告诉它操作已经完成,View 将设置焦点。

You could introduce an interface for the View so that the ViewModel can tell the View to set the Focus. The BookLibrary sample application of the WPF Application Framework (WAF) shows how to do it. Please have a look at the BookListViewModel.

The question has been asked a couple of times, unfortunately the answers only apply to WPF. So for silver light using MVVM, you can also bind with any property for detail please visit the following link

http://codenicely.blogspot.com/2012/01/how-to-set-textbox-focus-in-silverlight.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM