Home > database >  WPF Update List Box From Another View/Class
WPF Update List Box From Another View/Class

Time:09-23

Very new to WPF. I am trying to achieve something relatively simple that is proving to be difficult.

Basically, I want to add an Item to my List Box. The List Box is created in my LiveView xaml/class, but I want to update the contents of the List Box when I push a button in my SettingsView Class.

SettingsView class:

public partial class SettingsView : UserControl
   {
       public SettingsView()
           {
               InitializeComponent();
           }

       private void StartButton_Click(object sender, RoutedEventArgs e)
           {
               var myLiveView = new LiveView();
               myLiveView.updateListBox();
           }

}

LiveView class:

public partial class LiveView : UserControl
{
    public LiveView()
    {
        InitializeComponent();
    }

    public void updateListBox()
    {
        CommentListBox.Items.Add("Another item");
    }
}

If I do the following, the code works and an item is sucessfully added to my list on startup.

public partial class LiveView : UserControl
{
    public LiveView()
    {
        InitializeComponent();
        CommentListBox.Items.Add("Another item");
    }
}

Why can I only update the UI inside the Liveview class()? What is the right way to go about this? how can I update my ListBox from another class/view? The instance that I'm creating of LiveView doesn't appear to actually do anything. Any help would be much appreiated, thank you.

CodePudding user response:

When you create a new instance of user control so it is empty now, to handle this please check the delegates and events in both the user controls with respect parent and child navigation.

CodePudding user response:

Fixed using MVVM which made this whole process much easier.

  • Related