简体   繁体   English

C#和WPF:另一个类无法访问的控件

[英]C# and WPF: controls inaccessible from another class

I just started fiddling around with C# and WPF. 我刚刚开始摆弄C#和WPF。

Let's say that I want to instantiate a Black grid and that I want to randomly move around a red square in said Grid. 假设我要实例化“黑色”网格,并且要在所述网格中的红色正方形周围随机移动。

Currently I can basically do whatever I want as long as I keep everything in "MainWindow.xaml.cs"... 目前,只要将所有内容保留在“ MainWindow.xaml.cs”中,我基本上就可以做我想做的任何事情。

Now, my problem is that if I create a new class (eg, "MakeStuffHappen.cs") and from it I try to access the Grid (named "MyGrid") that will be instantiated by MainWindow's constructor, intellisense doesn't "see" it. 现在,我的问题是,如果我创建一个新类(例如“ MakeStuffHappen.cs”),然后从中尝试访问将由MainWindow的构造函数实例化的网格(名为“ MyGrid”),则intellisense不会“看到” ”。 I tried making a getter that returns "MyGrid" but then the compiler says that "an object reference is required for the non-static field, method, or property 'ProjectName.MainWindow.getGrid()'. Obviously I cannot define MainWindow as a static class... 我尝试制作一个返回“ MyGrid”的吸气剂,但是编译器说“非静态字段,方法或属性'ProjectName.MainWindow.getGrid()'需要对象引用。显然,我无法将MainWindow定义为静态类...

Any tips on how to solve this? 关于如何解决此问题的任何提示?

Thanks! 谢谢!

PS Since I'm evidently no programmer I'm not necessarily aware of the technical terms to use when looking up information... so I apologize in advance if this question has been already asked. PS:由于我显然不是程序员,因此我在查找信息时不一定知道要使用的技术术语……因此,如果已经提出此问题,我先向您道歉。

PPS I saw this: Access MainWIndow Control from a class in a separate file but it doesn't help. PPS我看到了这一点: 从单独文件中的类访问MainWIndow控件,但这没有帮助。

Once your view is initialized (when the OnInitialized event fires) you can pass the initialized Grid into your helper class: 初始化视图后(触发OnInitialized事件时),您可以将初始化的Grid传递到您的帮助器类中:

MainWindow.xaml.cs: MainWindow.xaml.cs:

public partial class MainWindow 
{
    MakeStuffHappen helper = null;
    public MainWindow()
    { 
       OnInitialized += (s,e)=> { helper = new MakeStuffHappen(this.MyGridName); } 
    }
}

MakeStuffHappen.cs MakeStuffHappen.cs

public class MakeStuffHappen
{
    Grid theGrid = null;
    public MakeStuffHappen(Grid grid)
    {
        theGrid = grid;
        // Do stuff with the grid.
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM