RoutedEventHandler未正确添加到指定的元素

时间:2012-07-02 21:39:24

标签: c# wpf routed-events

我正在尝试使用以下代码行将RoutedEventHandler添加到所有TextBoxes代码中:

this.AddHandler(TextBox.GotFocusEvent, new RoutedEventHandler(textBox_GotFocus));

上面的代码将处理程序绑定到Window上的所有表单控件而不是单独的TextBoxes。请有人

  1. 解释为什么会发生这种情况
  2. 以及如何正确行事。
  3. 谢谢。

1 个答案:

答案 0 :(得分:1)

可能不完全是你所追求的,因为它仍然会触发每个UIElement。但是,您可以执行以下操作以获得所需的“最终结果”。

    public void textBox_GotFocus(object sender, RoutedEventArgs e)
    {
        var textBox = e.Source as TextBox;

        if (textBox == null)
            return;

        //what ever you wanted to do
    }