简体   繁体   English

WPF中的集体事件处理程序

[英]Collective Event Handler in WPF

On my WPF Window, I want the textboxes to have a slightly blue background when the cursor is on them. 我希望在WPF窗口中,当光标位于文本框上时,它们的背景会略带蓝色。 I created two simple event handlers (GotFocus and LostFocus) to do this. 我创建了两个简单的事件处理程序(GotFocus和LostFocus)来执行此操作。

private void textBox1_GotFocus(object sender, RoutedEventArgs e)
        {
            textBox1.Background = (Brush)new BrushConverter().ConvertFrom("#FFE6E6FF");
        }

        private void textBox1_LostFocus(object sender, RoutedEventArgs e)
        {
            textBox1.Background = Brushes.White;
        }

Is there a way I can direct every textbox to one eventhandler that gives the background to the respective textbox? 有没有一种方法可以将每个文本框定向到一个为相应文本框提供背景的事件处理程序?

Very simple. 很简单。 Put the event hook on the outermost container of all of the text boxes: 将事件挂钩放在所有文本框的最外面的容器上:

<Window TextBox.GotFocus="textBox1_GotFocus" TextBox.LostFocus="textBox1_LostFocus">
   <TextBox ... >
   <TextBox ... >
   <TextBox ... >
</Window>

To make it operate on the correct textbox, cast the "sender" parameter as a textbox: 为了使其在正确的文本框上运行,请将“ sender”参数转换为文本框:

private void textBox1_GotFocus(object sender, RoutedEventArgs e)
{
    ((TextBox)sender).Background = (Brush)new BrushConverter().ConvertFrom("#FFE6E6FF");
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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