当某个事件在WPF中的另一个窗口上触发时,如何在一个窗口上更新列表

当某个事件在WPF中的另一个窗口上触发时,如何在一个窗口上更新列表。 我只想知道如何从另一个窗口听一个窗口的事件。

您必须将对象传递给新窗口,然后在第二个窗口上为它创建一个新的事件处理程序。

在此处输入图像描述

第一个窗口代码:

public FirstWindow() { InitializeComponent(); } private void Window_Loaded(object sender, RoutedEventArgs e) { SecondWindow sWindow = new SecondWindow(btnFirstWindow); sWindow.Show(); } 

第二窗口代码:

 private Button firstWindowButton; public SecondWindow(Button firstWindowButton) { this.firstWindowButton = firstWindowButton; InitializeComponent(); } private void Window_Loaded(object sender, RoutedEventArgs e) { firstWindowButton.Click += firstWindowButton_Click; } void firstWindowButton_Click(object sender, RoutedEventArgs e) { lblShowUser.Content = "First window button clicked on: " + DateTime.Now.ToString(); } 

我已经为第一个窗口添加了一个列表,并为您添加了第二个窗口中的事件:

在此处输入图像描述

这是第一个Windows代码:

 public FirstWindow() { InitializeComponent(); } private void Window_Loaded(object sender, RoutedEventArgs e) { String[] items = { "Item 1", "Item 2", "Item 3" }; listItems.ItemsSource = items; SecondWindow sWindow = new SecondWindow(btnFirstWindow, listItems); sWindow.Show(); } 

第二个Windows代码:

 private Button firstWindowButton; private ListBox firstWindowListBox; public SecondWindow(Button firstWindowButton, ListBox firstWindowListBox) { this.firstWindowButton = firstWindowButton; this.firstWindowListBox = firstWindowListBox; InitializeComponent(); } private void Window_Loaded(object sender, RoutedEventArgs e) { firstWindowButton.Click += firstWindowButton_Click; firstWindowListBox.MouseDoubleClick += firstWindowListBox_MouseDoubleClick; } void firstWindowListBox_MouseDoubleClick(object sender, MouseButtonEventArgs e) { if (firstWindowListBox.SelectedItem != null) { lblShowUser.Content = "First window list box selected item: " + firstWindowListBox.SelectedItem.ToString(); } } void firstWindowButton_Click(object sender, RoutedEventArgs e) { lblShowUser.Content = "First window button clicked on: " + DateTime.Now.ToString(); } 

到目前为止你做了什么?

是一个窗口创建另一个窗口?

通常我会调用子窗口的方法。 如果子窗口想要触发父窗口,则应该使用事件来完成。

喜欢:

 public class FormParent : Form { public void OpenChild() { // create the child form FormChild child = new FormChild(); // register the event child.DataUpdated += Child_DataUpdated; // .... // parent to child (method call) child.DoSomething(); } public void Child_DataUpdated(object sender, EventArgs e) { // refresh the list. } } public class FormChild : Form { public void DoSomething() { // .... // if the list should be refreshed. // call event from child to parent. if(DataUpdated != null) DataUpdated(this, EventArgs.Empty); } public event EventHandler DataUpdated; } 

请记住,父母知道孩子的结构。 (方法调用)孩子,对父母的结构一无所知(事件)

这样您就可以在不同的解决方案上重用孩子。 (不依赖于代码)

这基本上是在两个窗口之间传递数据的问题。 发送者是有触发器的窗口, 接收器是什么过程。

你可以有一个耦合的解决方案,当一个窗口应该知道其他。 如果你将接收者的实例传递给发送者,那么发送者将能够调用接收者的公共方法。 如果你将发送者的实例传递给接收者,那么接收者可以订阅公共控制事件(不要这样做)或特殊的专用forms事件 (仅仅因为这个原因 – 触发其他地方的事情)。

解耦解决方案是具有单独的类(提供程序?),它公开事件和方法以触发该事件。 接收方将订阅事件,发送方将触发它,它们都不知道彼此,没有必须触发或订阅。