首页 > 解决方案 > 从另一个窗口访问 MainWindow 列表(保护)

问题描述

我在 WPF 应用程序中的 MainWindow.xaml.cs 中有这段代码

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);


    }

我想在另一个 xaml.cs 中使用“listafiguras”ObservableCollection,如下所示:

 public partial class Preferences : Window
{


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

但它说 MainWindow 由于其保护级别而无法访问。如何更改它以访问我的变量?谢谢

标签: c#wpfxamlmainwindow

解决方案


listafiguras 对您的 MainWindow 类是私有的,因此 Mainwindow 之外的任何东西都无法访问。您也许可以将此列表作为构造函数参数传递给 Preferences :

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

在主窗口中:

Preferences = new animaciones.Preferences(listafiguras );

但是,我建议您考虑使用服务和 DI 框架在视图之间共享数据,以便为此类问题提供更通用的解决方案(请参阅“WPF 服务到底是什么?”


推荐阅读