确定我的WPF中哪个控件通过脚本聚焦

时间:2017-04-16 01:49:28

标签: c# wpf xaml

如何确定哪个控件在C#中具有焦点?

示例:

private void button_Click(object sender, RoutedEventArgs e)
{
    Update(Brushes.White, textBox);   /*Here there my textBox has focus.*/

    //... (some codes)

    NotCorrect();

    //... (some codes)
}

private void NotCorrect()
{
    Update(textblock.background, /*I mean here : the focus remains where it is already, on the textBox.*/);
    textBlock.text = "Try again..."
}

private void Update(Brushes myBrush, Control myControl)
{
    texBlock.Background = myBrush;
    myControl.Focus();
}

在NotCorrect()方法中:

textBlock.Background意味着:我想要与现有刷子相同的刷子(参见Click事件的第一行),我不想改变任何东西。

(我更喜欢编写textBlock.Background而不是重写Brushes.White。)

现在我问是否还有一种说法:我希望焦点保持在已经控制的位置,我不想改变任何东西。

2 个答案:

答案 0 :(得分:1)

Form.ActiveControl是你应该搜索的。

答案 1 :(得分:0)

  • 我发现了一种使用null的解决方案:

    private void button_Click(object sender, RoutedEventArgs e)
    {
        Update(Brushes.White, textBox);
    
        //... (some codes)
    
        NotCorrect();
    
        //... (some codes)
    }
    
    private void NotCorrect()
    {
        Update(textblock.background, null);
        textBlock.text = "Try again..."
    }
    
    private void Update(Brushes myBrush, Control myControl)
    {
        texBlock.Background = myBrush;
        if (myControl != null)
            myControl.Focus();
    }
    
  • 我找到的另一个更简单的解决方案是使用this

    private void button_Click(object sender, RoutedEventArgs e)
    {
        Update(Brushes.White, textBox);
    
        //... (some codes)
    
        NotCorrect();
    
        //... (some codes)
    }
    
    private void NotCorrect()
    {
        Update(textblock.background, this);
        textBlock.text = "Try again..."
    }
    
    private void Update(Brushes myBrush, Control myControl)
    {
        texBlock.Background = myBrush;
        myControl.Focus();
    }