如何从静态 class 更改 UserControl 属性?

How to change UserControl property from static class?

我在 MainWindow.xaml 中有 GridGrid填的是我的UserControl(修改Button).

在静态 class 全局变量中,我有 bool 变量,它在按下 Button 时发生变化。现在我还需要更改此 bool 变量更改的 Grid 背景颜色。

问题是,我无法从 MainWindow.xaml.cs 代码后面的其他地方到达 Grid

Global.cs:

public static class Globals
    {
        private static bool _player;
        public static bool Player {
            get { return _player; }

            set {
                _player = value;
                Debug.WriteLine(value);
            }
        }
    }

我的UserControl:

public partial class tetrisButton : UserControl
    {
        public tetrisButton()
        {
            InitializeComponent();
            Button.Focusable = false;
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            if(!Globals.Player)
            {
                Button.Content = new cross();
                Globals.Player = true;
            }
            else
            {
                Button.Content = new circle();
                Globals.Player = false;
            }

        }
    }

如果您不实现 MVVM 模式(或类似模式),您可以只获取包含的网格并设置颜色:

public partial class tetrisButton : UserControl
{
    public tetrisButton()
    {
        InitializeComponent();
        Button.Focusable = false;
    }

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        Grid parent = FindParent<Grid>(this);

        if(!Globals.Player)
        {
            Button.Content = new cross();
            Globals.Player = true;
            parent.Background = Brushes.Blue;
        }
        else
        {
            Button.Content = new circle();
            Globals.Player = false;
            parent.Background = Brushes.Red;
        }

    }

    private T FindParent<T>(DependencyObject child) where T : DependencyObject
    {
         T parent = VisualTreeHelper.GetParent(child) as T;

         if (parent != null)
             return parent;
         else
             return FindParent<T>(parent);
    }
}

您可以使用 Window.GetWindow 方法获取对 UserControl 的父 window 的引用:

private void Button_Click(object sender, RoutedEventArgs e)
{
    MainWindow mainWindow = Window.GetWindow(this) as MainWindow;
    if (!Globals.Player)
    {
        Button.Content = new cross();
        Globals.Player = true;

        if (mainWindow != null)
            mainWindow.grid.Background = Brushes.Green;
    }
    else
    {
        Button.Content = new circle();
        Globals.Player = false;

        if (mainWindow != null)
            mainWindow.grid.Background = Brushes.Red;
    }
}

为了能够访问 Grid,您可以在 MainWindow.xaml 的 XAML 标记中给它一个 x:Name:

<Grid x:Name="grid" ... />