Home > other >  How can i acces my ObservableCollection from another class C# mvvm to add Items to that collection
How can i acces my ObservableCollection from another class C# mvvm to add Items to that collection

Time:03-15

This is my first class from where i am making tabs and i want to add my tabs to the ObservableCollection

 namespace Notepad__.ViewModel
{
public class TabViewModel
{
    public DocumentModel m_doc;

    public  ObservableCollection<TabItem> Tabs { get; set; }
    public TabViewModel()
    {
        Tabs = new ObservableCollection<TabItem>();
        Tabs.Add(new TabItem { Header = "s", Content = "One's content" });
        Tabs.Add(new TabItem { Header = "Two", Content = "Two's content" });
    }
    public  class TabItem
    {
        public string Header { get; set; }
        public string Content { get; set; }
    }
}
}

This is the class from where i want to access the Collection to add a new tab. When a new File is created i want to add that file to collection and my Tab Control to update the tab items

namespace Notepad__.ViewModel
{
public class FileModel
{
    public DocumentModel Document { get; private set; }
        
    public ICommand NewCommand { get; }
    public ICommand SaveCommand { get; }
    public ICommand OpenCommand { get; }
    public ICommand SaveAsCommand { get; }


public FileModel(DocumentModel document)
    {
        Document = document;
        NewCommand = new RelayCommand(NewFile);
        SaveCommand = new RelayCommand(SaveFile);
        SaveAsCommand = new RelayCommand(SaveFileAs);
        OpenCommand = new RelayCommand(OpenFile);
    }

    public void NewFile()
    {
        Document.FileName = "New File";
        Document.FilePath = string.Empty;
        Document.Text = string.Empty;
        //TabViewModel.TabItem("")
    }

CodePudding user response:

How can i acces my ObservableCollection from another class C#

Make the collection static.

public static  ObservableCollection<TabItem> Tabs { get; set; }

Then access as such

 TabViewModel.Tabs.Add(...);

Note the WPF preference for this situation is to create the viewmodel reference on the app as a static, then reference it by the main page and others. Such as App.VM.Tabs.Add().

CodePudding user response:

yeah that worked thx a lot for the time :D

  • Related