Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/wpf/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何在MainWindow中创建实例并在其他类中使用_C#_Wpf - Fatal编程技术网

C# 如何在MainWindow中创建实例并在其他类中使用

C# 如何在MainWindow中创建实例并在其他类中使用,c#,wpf,C#,Wpf,我有一个严重的问题,我正在尝试在MainWindow类中创建一个实例,如下所示: public MainWindow() { InitializeComponent(); AppWindow = this; CalenderBackground background = new CalenderBackground(Calendar); } 我需要在主窗口中显示这个距离,因为类CalendarBackground有一个方法可以刷新插入日历的上一个日期,我正在使用资

我有一个严重的问题,我正在尝试在MainWindow类中创建一个实例,如下所示:

public MainWindow()
{
     InitializeComponent();
     AppWindow = this;
     CalenderBackground background = new CalenderBackground(Calendar);
}
我需要在主窗口中显示这个距离,因为类CalendarBackground有一个方法可以刷新插入日历的上一个日期,我正在使用资源

我想在类
装置中使用对象
背景

class Fixtures
{
     MainWindow.Calendar.Background = background.GetBackground();
}

但实际上我不能创建这个,因为我看不到变量
background
,为什么?

通过构造函数将background对象传递到fixture中

CalenderBackground background = new CalenderBackground(Calendar);
Fixtures fixtures;

public MainWindow()
{
     InitializeComponent();
     AppWindow = this;
     fixtures = new Fixtures(background);
}

class Fixtures
{
    public Fixtures(Background background)
    {
        MainWindow.Calendar.Background = background.GetBackground();
    }
}

您在MainWindow方法的作用域中将background声明为变量。为了能够在Fixtures类中访问它,您需要将它作为参数传递给构造函数,然后使用它设置字段,例如:

private CalenderBackground _background;

public Fixtures(CalenderBackground background)
{
   _background = background;
}
或者您可以在主窗口上创建一个公共窗口,并从Fixtures类访问它

public CalenderBackground Background {get; set;}

因为您在构造函数中声明了
background
,所以在构造函数之外不会看到它。声明类型为
CalendarBackground
的局部变量,并在构造函数中初始化背景。我已经尝试过,但如果我将该变量移出构造函数,编译器将返回以下消息:字段初始值设定项不能引用属性、方法或字段不是静态MainWindows。CalendarIn MainWindow构造函数,为什么不直接做“Calendar.Background=新日历背景(Calendar);”公共静态日历;类型主窗口已包含日历的定义。Calendar是XAML GUIRemove“public static Calendar Calendar;”我遇到了以下错误:字段初始值设定项无法引用属性,方法或字段不是静态MainWindows。Calendar;在日历背景上=新的日历背景(日历);特别是日历(参数)用红色下划线