c# - 从另一个窗口访问 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 由于其保护级别而无法访问。如何更改它以访问我的变量?谢谢
解决方案
listafiguras 对您的 MainWindow 类是私有的,因此 Mainwindow 之外的任何东西都无法访问。您也许可以将此列表作为构造函数参数传递给 Preferences :
public Preferences(ObservableCollection<Figura> figuraList)
{
InitializeComponent();
tabla.ItemsSource = figuraList;
}
在主窗口中:
Preferences = new animaciones.Preferences(listafiguras );
但是,我建议您考虑使用服务和 DI 框架在视图之间共享数据,以便为此类问题提供更通用的解决方案(请参阅“WPF 服务到底是什么?”)
推荐阅读
- button - 在自定义按钮上刷新页面后,面包屑被转换为仅记录名称单击树视图
- fortran - 在fortran中将整数转换为双精度
- yarnpkg - 是否有一个 yarn 命令可以显示所有软件包的安装路径?
- go - 如何维护一组整数序列?
- wordpress - 如何在 wordpress 网站上为广告添加占位符 Div?
- wordpress - 不同wordpress目录的子域
- django - 当我发布文件数据时,它包含空值
- java - 如何在 spring mvc 的 api 配置文件中启用 Jpa 审计?
- http-headers - 是否可以强制服务器发送原始/解码响应?任何人都可以有提琴手或邮递员演示来证明吗?
- c++ - C++ while 循环 v[i++] 与 while 主体中的 i++