locked
Display a collection from another class RRS feed

  • Question

  • Hi everyone.

    There is a WPF application and a collection exists in one of the classes ObservableCollection.

    In the current view, so that the ListBox displays the contents of the collection implements the following process:

    public

    public someClass()
    {
        ObservableCollection<SomeType> messages = new ObservableCollection<SomeType>();
    
        private async void GetMessagesUpdate()
        {
          // Many strings of code
          messages.Add(new SomeStruct (string1, string2, string3));
         // Many strings of code
        }
    
        public ObservableCollection<SomeType> SomeMethod()
        {
          return messages
        }
    }

    And in the MainWindow

    ObservableCollection<SomeType> messages = new ObservableCollection<SomeType>();
    commandViewer.ItemsSource = messages; private void Button_Click(object sender, RoutedEventArgs e) { ObservableCollection<SomeType> temp = SomeClass.messages(); foreach (var item in temp) { messages.Clear(); messages.Add(new SomeStruct(string1, string2, string2)); } }

    I am sure that there is an easier way to transfer collections between classes without creating intermediate collections.
    Is it possible to implement the code in such a way that ListBox would pick up a collection change from another class?





    Monday, October 12, 2020 10:36 AM

All replies

  • Hi DenisAndreevich,
    For questions about WPF, I suggest you ask the questions in Microsoft Q&A forum and you can get more professional answer.
    Thank you for your understanding.
    Best Regards,
    Daniel Zhang


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.


    Tuesday, October 13, 2020 3:20 AM
  • Thanks. I created my question on that forum. You can delete this question :)
    Tuesday, October 13, 2020 3:25 AM
  • I am sure that there is an easier way to transfer collections between classes without creating intermediate collections.
    Is it possible to implement the code in such a way that ListBox would pick up a collection change from another class?

    Yeah it's called dependency injection. The collection is an object. The object can be passed to another class on the called class's contractor aka constructor injection.

    https://stackify.com/dependency-injection-c-sharp/

    https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/using-constructors

    Tuesday, October 13, 2020 4:56 AM