如何在c#中将对象传递给事件处理程序?

如何在c#中将对象传递给事件处理程序?,c#,events,event-handling,C#,Events,Event Handling,我希望能够访问sampleDropDown事件处理程序中的authorText对象。 将对象声明移到Button_Click方法的范围之外不是一个有效的解决方案,因为我需要在每次单击按钮时创建一个新对象 我需要创建一个新的对象,每次点击一个按钮 如果您确实需要一个新对象,您仍然可以在类级别保留对集合中每个对象的引用。然后,在每个按钮中单击处理程序创建一个新对象并将其添加到列表中 public void Button_Click(object sender, RoutedEventArgs e)

我希望能够访问sampleDropDown事件处理程序中的authorText对象。 将对象声明移到Button_Click方法的范围之外不是一个有效的解决方案,因为我需要在每次单击按钮时创建一个新对象

我需要创建一个新的对象,每次点击一个按钮

如果您确实需要一个新对象,您仍然可以在类级别保留对集合中每个对象的引用。然后,在每个
按钮中单击
处理程序创建一个新对象并将其添加到列表中

public void Button_Click(object sender, RoutedEventArgs e)
    {
        TextBlock authorText = new TextBlock();
        authorText.Text = "Saturday Morning";
        authorText.FontSize = 12;
        authorText.FontWeight = FontWeights.Bold;
        authorText.PreviewMouseDown += new MouseButtonEventHandler(test1);
        authorText.Visibility = System.Windows.Visibility.Collapsed;

        Grid.SetColumn(authorText, 0);

        sp_s.Children.Add(authorText);
    }


void sampleDropDown(object sender, RoutedEventArgs e)
    {

    }

authorText
的引用保存在
sp_.Children
中。除非在
sampleDropDown()
处理程序中需要引用之前将其删除,否则您可能可以在那里访问它。

通常
RoutedEventArgs
会针对此类情况进行扩展,但声明为实例变量(至少在这种情况下)并无害处。另外,我没有看到在您的案例中显式调用了
sampleDropDown
,我建议为此类案例创建类变量。什么是
sampleDropDown
处理程序,它在哪里分配?
List<TextBlock> authorTextList = new List<TextBlock>();

public void Button_Click(object sender, RoutedEventArgs e)
{
    TextBlock authorText = new TextBlock();
    authorTextList.Add(authorText);

    /// ...
}

void sampleDropDown(object sender, RoutedEventArgs e)
{
    /// ... access List objects here as desired
}
sp_s.Children.Add(authorText);