WPF将焦点设置为在运行时添加的UserControl [英] WPF Setting focus to UserControl added at runtime

查看:62
本文介绍了WPF将焦点设置为在运行时添加的UserControl的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道在这个问题上已经进行了很多讨论,但是我恐怕没有得到它.我有一个父用户控件,正在运行时向其添加子用户控件.子UserControl有一个菜单.在子UserControl拥有键盘焦点之前,菜单项不会启用.子用户控件添加了按钮的click事件.

如何将焦点设置到子UserControl?

我尝试过Focus()和KeyBoard.Focus的各种变体都没有用.焦点停留在父级UserControl的单击按钮上.

I know there has been much discussion on this subject but I''m afraid I do not get it. I have a Parent UserControl to which I am adding a Child UserControl at runtime. The Child UserControl has a menu. The Menu items are not enabled until the Child UserControl has keyboard focus. The Child UserControl is added with the click event of a button.

How do I set the focus to the Child UserControl?

I have tried all sorts of variations of Focus() and KeyBoard.Focus to no avail. The focus remains on the clicked button of the Parent UserControl.

class ParentUserControl
{
    public void ChangeContent(UIElement newContent)
    {
        var userControl = newContent as IBaseUserControl;
        if (userControl == null)
        {
            throw new NoNullAllowedException();
        }

        if (GridControl.Children.Count == 0)
        {
            GridControl.Children.Add(newContent);
            userControl.GetObservableCollection();
        }
        else
        {
            GridControl.IsHitTestVisible = false;
            var oldContent = GridControl.Children[0];

            EventHandler onAnimationCompletedHandler = delegate
            {
                GridControl.IsHitTestVisible = true;
                GridControl.Children.Remove(oldContent);
                userControl.GetObservableCollection();
            };

            FadeAnimation(newContent, oldContent, onAnimationCompletedHandler);
        }

        // None of these work
        //GridControl.Focus();
        //newContent.Focus();
        //Keyboard.Focus(newContent);
        Keyboard.Focus(GridControl);
    }

}

推荐答案

设置newContent.Focus()....或者尝试以下操作:

http://blogs.imeta.co.uk/jpanni/存档/2008/12/30/wpf-uielement.focus.aspx [ http://msdn.microsoft.com/en-us/library/system. windows.uielement.focusable.aspx [ ^ ]
Set the newContent.Focus().... And or try some of these:

http://blogs.imeta.co.uk/jpanni/archive/2008/12/30/wpf-uielement.focus.aspx[^]

If the usercontrol xaml markup can be changed, make sure you set the Focusable property to true.

http://msdn.microsoft.com/en-us/library/system.windows.uielement.focusable.aspx[^]


这篇关于WPF将焦点设置为在运行时添加的UserControl的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆