How to update list on one window when some event trigger on another window in WPF

后端 未结 3 1369
忘了有多久
忘了有多久 2021-01-25 15:40

How to update list on one window when some event trigger on another window in WPF. i just want to know how to listen to the event of one window from another window.

3条回答
  •  渐次进展
    2021-01-25 16:23

    You'll have to pass the object to the new window and then create a new event handler for it on the second window.

    enter image description here

    First Window Code:

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

    Second Window Code:

    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();
    }
    

    I've added a list to the first window and events on the second window for you:

    enter image description here

    Here is the first windows code:

    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();
    }
    

    Second windows code:

    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();
    }
    

提交回复
热议问题