C# 从另一个窗口访问主窗口列表(保护)
我这里有一个WPF应用程序中MainWindow.xaml.cs的代码C# 从另一个窗口访问主窗口列表(保护),c#,wpf,xaml,mainwindow,C#,Wpf,Xaml,Mainwindow,我这里有一个WPF应用程序中MainWindow.xaml.cs的代码 public partial class MainWindow : Window { animaciones.Preferences Preferences; animaciones.GameOver GameOver; ObservableCollection<Figura> listafiguras = new ObservableCollection<Figura>()
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);
}
但该公司表示,由于其保护级别,无法访问MainWindow。我如何更改它以访问我的变量?谢谢listafiguras是您的MainWindow类私有的,因此无法访问MainWindow之外的任何内容。您可以将此列表作为构造函数参数传递给首选项:
public Preferences(ObservableCollection<Figura> figuraList)
{
InitializeComponent();
tabla.ItemsSource = figuraList;
}
但是,我建议您考虑使用服务和DI框架在视图之间共享数据,以便为此类问题提供更通用的解决方案(请参阅)我尝试过!现在它说:参数类型“ObservableCollection”比方法“Preferences”更难访问。Preferences(ObservableCollection)Figura(private,public)的可访问性是什么?public Figura(){}是的,它工作了!我只是把公共类的数字,而不是唯一的类的数字。。多谢各位!很好,但请考虑使用接口/服务包装共享数据,并将这些接口注入到您的视图中,正如我回答中的链接所描述的那样。
public Preferences(ObservableCollection<Figura> figuraList)
{
InitializeComponent();
tabla.ItemsSource = figuraList;
}
Preferences = new animaciones.Preferences(listafiguras );