【问题标题】:Accessing a MainWindow list from another window (Protection)从另一个窗口访问 MainWindow 列表(保护)
【发布时间】:2020-02-07 16:35:05
【问题描述】:

我在 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# wpf xaml mainwindow


    【解决方案1】:

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

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

    在主窗口中:

    Preferences = new animaciones.Preferences(listafiguras );
    

    不过,我建议您考虑使用服务和 DI 框架在视图之间共享数据,以便为此类问题提供更通用的解决方案(请参阅 What exactly are "WPF services"?

    【讨论】:

    • 我试过了!现在它这样说:参数类型 'ObservableCollection' 比方法 'Preferences.Preferences(ObservableCollection) 更难访问
    • Figura 的可访问性是什么(私有、公共)?
    • 公开 Figura(){}
    • 是的,它成功了!我只是放了 public class Figura 而不是只有 class Figure .. 非常感谢!
    • 很好,但请考虑使用接口/服务来包装共享数据,并将这些接口注入到您的视图中,正如我的答案中的链接所描述的那样。
    猜你喜欢
    • 1970-01-01
    • 2011-06-24
    • 2016-08-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多