假设我们有一个通用的按钮列表,每次运行程序时,都会生成未知数量的按钮并将其添加到该列表中。(所以按钮的数量并不总是恒定的)我想知道我怎样才能为这个列表中的这些按钮编写方法(button.click)。你有什么想法可以帮助我吗?
1 回答
0
我将补充@aepot 评论:
private readonly List<Button> buttons = new List<Button>();
private void AddButton(Button button)
{
button.Click += Button_Click;
buttons.Add(button);
}
private void RemoveButton(Button button)
{
button.Click -= Button_Click;
buttons.Remove(button);
}
private void Button_Click(object sender, RoutedEventArgs e)
{
// Checking the event source for compatibility with the Button
// and the presence of this button in the list
if (sender is Button button && buttons.Contains(button))
{
//Here you can work with the button that caused the event
}
}
但是@Clemens 的建议更好。WPF 通常在 XAML 中创建 UI 元素。XAML 是 WPF 的核心语言。
于 2020-07-16T06:17:09.403 回答