YWah
YWah

Reputation: 579

How to update the content of wpf listbox from different window

I've two windows: Main Window, Log Window. How can I update the listbox in the Log Window when some action is happened in the Main Window (e.g. button is clicked)?

Below is the code for listbox in Log Window:

<ListBox x:Name="DebugLogLb" BorderBrush="{x:Null}">  
  <TextBlock x:Name="DebugLogTb" Text="{Binding LogText}" Background="{x:Null}" />
</ListBox>

When the button in the Main Window is clicked, it will update the listbox. I tried with the code below but it doesn't work.

private void Btn1_Click(object sender, RoutedEventArgs e)
{
    var log = new LogWindow();
    log.DebugLogLb.Items.Add(new { LogText = "Button 1 is clicked" });
}

I'm able to update the listbox if I put everything in the same window, but I failed to do so with two windows.

My expected output would be like: enter image description here

Even if both windows are opened, when the buttons in the Main Window are clicked, it will directly update in the Log Window as well.

Thanks for any helps in advanced.

Upvotes: 0

Views: 1103

Answers (1)

user2697817
user2697817

Reputation: 1498

It's hard to tell where you are going wrong without seeing more of the code. This is an example that works. It creates a new LogWindow in the MainWindow ctor and sets the DataContext. When the button is clicked the handler calls show on the window. The ListBox's itemssource property is bound to an ObservableCollection of strings. So any adds/removes are automatically updated on the UI.

LogWindows xaml

<Window x:Class="WpfApplication7.LogWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="LogWindow" Height="300" Width="300">
<Grid>
    <ListBox x:Name="DebugLogLb" BorderBrush="{x:Null}" ItemsSource="{Binding LogText}" />
</Grid>


MainWindow code-behind

public partial class MainWindow : Window
{
    LogWindow _logWindow;

    public MainWindow()
    {
        InitializeComponent();

        LogText = new ObservableCollection<string>();

        _logWindow = new LogWindow();
        _logWindow.DataContext = this;
        _logWindow.Closed += _logWindow_Closed;
    }

    private void _logWindow_Closed(object sender, EventArgs e)
    {
        _logWindow = new LogWindow();
    }

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        _logWindow.Show();

        LogText.Add("Button1 Clicked");
    }

    public ObservableCollection<string> LogText { get; set; }
}

Upvotes: 3

Related Questions