Samuel
Samuel

Reputation: 75

WPF- How can i use a List that i declare and fill in my MainWindow in a Usercontrol?

Hi i need to be able to use a list from my Main Window in a Usercontrol i need to be able to edit and read from it in various Usercontrols.

MainWindow:

public partial class MainWindow : Window
{
    public List<Termin> termine = new List<Termin>();

    public MainWindow()
    {
        InitializeComponent();
    }
}

Usercontrol:

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

    private void SomeMethod()
    {
        //i need to be able to use the list here
    }

}

Upvotes: 1

Views: 246

Answers (1)

mm8
mm8

Reputation: 169340

You need to get a reference to the MainWindow one way or another. The easiest way to do this is probably to use the Application.Current.Windows property:

private void SomeMethod()
{
    var mw = Application.Current.Windows.OfType<MainWindow>().FirstOrDefault();
    List<Termin> termine = mw.termine;
    //...
}

You could also consider making termine static:

public partial class MainWindow : Window
{
    public static List<Termin> termine = new List<Termin>();

    public MainWindow()
    {
        InitializeComponent();
    }
}

...and access it directly without a reference to an instance of MainWindow:

private void SomeMethod()
{
    List<Termin> termine = MainWindow.termine;
    //...
}

Upvotes: 1

Related Questions