dantosh
dantosh

Reputation: 1

Accessing a MainWindow list from another window (Protection)

I have this code over here from MainWindow.xaml.cs in a WPF application

public partial class MainWindow : Window
{

    animaciones.Preferences Preferences;
    animaciones.GameOver GameOver;
    ObservableCollection<Figura> listafiguras = new ObservableCollection<Figura>();
    System.Media.SoundPlayer player = new System.Media.SoundPlayer();
    DispatcherTimer timer;
    Raton raton;

    public MainWindow()
    {
        InitializeComponent();
        Preferences = new animaciones.Preferences();
        GameOver = new animaciones.GameOver();
        raton = new Raton();
        player.SoundLocation = "lostwoods.wav";
        Canvas.SetLeft(raton.fig, raton.x);
        Canvas.SetBottom(raton.fig, raton.y);
        lienzo.Children.Add(raton.fig);

        this.KeyDown += new KeyEventHandler(KeyDownEventos);

        timer = new DispatcherTimer();
        timer.Tick += OnTick;
        timer.Interval = new TimeSpan(0, 0, 0, 0, 50);


    }

I want to use the "listafiguras" ObservableCollection in another xaml.cs like this:

 public partial class Preferences : Window
{


    public Preferences()
    {
        InitializeComponent();
        tabla.ItemsSource = MainWindow.listafiguras;
    }

But it says MainWindow is not accesible due its protection level. How can I change that to give access to my variable? Thank you

Upvotes: 0

Views: 454

Answers (1)

auburg
auburg

Reputation: 1475

listafiguras is private to your MainWindow class and thus not accessible to anything outside of Mainwindow. You can perhaps pass this list as a constructor parameter to Preferences :

public Preferences(ObservableCollection<Figura> figuraList)
    {
        InitializeComponent();
        tabla.ItemsSource = figuraList;
    }

In MainWindow:

Preferences = new animaciones.Preferences(listafiguras );

However i suggest you look into using services and DI frameworks for sharing data between views for a more general solution to this type of problem (see What exactly are "WPF services"?)

Upvotes: 1

Related Questions