C# 通过脚本确定WPF中哪个控件具有焦点
如何确定哪个控件在C#中具有焦点 例如:C# 通过脚本确定WPF中哪个控件具有焦点,c#,wpf,xaml,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 NotCorrec
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而不是重写笔刷.White。)
现在我问是否还有一种方式可以说:我希望焦点保持在它已经存在的控件上,我不想更改任何内容。Form.ActiveControl是您应该搜索的
- 我发现了一种使用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(); }
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(); }
- 我发现的另一个更简单的解决方案是使用
:这个
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(); }
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(); }