简体   繁体   中英

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
    }

}

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;
    //...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM