如何确定哪个控件在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。)
现在我问是否还有一种说法:我希望焦点保持在已经控制的位置,我不想改变任何东西。
答案 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();
}