如何将用户控件对象传递给另一个用户控件的内容?

How to pass the user control object to content of another user control?

我正在用 WPF C# 制作贪吃蛇游戏,我为不同的 "views" 创建了一些用户控件,这意味着我有 MainWindow 继承自 Window class 和几个用户控件及其 xaml 文件。 一个用户控件代表主菜单,另一个代表选项视图等。

public partial class MainWindow: Window
{
    public static Menu menu;
    public MainWindow()
    {
        InitializeComponent();
        menu = new Menu();
        this.Content = menu;
    }
}

像上面一样,在 MainWindow 中我创建了 Menu 对象(它是用户控件之一 - class 和 xaml 文件)并设置 [=29= 的内容] 到菜单的内容。然后在菜单 class 中我做同样的事情,例如用户单击带有文本 "options" 的按钮,他会转到选项用户控件。我只是

this.Content = new Options(); //"this" is now menu class

当他点击带有文字 "singleplayer" 的按钮时,他进入单人游戏的用户控制

this.Content = new Game();

等等。 通过这种方式,一切正常,我可以在不同的用户控件和 "load" 应用程序 Window 的不同内容之间切换,但每次我创建新对象时,这就是问题所在。当我转到选项然后返回菜单时,正在创建菜单 class 的新对象,我不记得以前的设置等。我只想创建一次然后引用这个 - 加载现有对象内容。我尝试使用绑定,但它不起作用。 我可以这样做吗?如何在不丢失数据且每次都创建新对象的情况下在不同的用户控件之间切换?

你应该使用 singletons.

单例允许您只有一个 class 实例。这样,每次操作实例时,您操作的都是同一个实例。这允许您通过代码保持/更新同一实例的状态。

看起来像这样,而且是线程安全的。

public sealed class YourClass
{
    private static readonly YourClass instance = new YourClass();

    /* Explicit static constructor to tell C# compiler
     * not to mark type as beforefieldinit */
    static YourClass()
    {

    }

    private YourClass()
    {

    }

    public static YourClass Instance
    {
        get
        {
            return instance;
        }
    }
}

编辑:OP 的错误是将用户控件的内容设置为 istelf 而不是 MainWindow 用户控件。在usercontrol中使用这行代码可以得到当前包含usercontrol的window。

Window yourParentWindow = Window.GetWindow(this);