繁体   English   中英

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

[英]How to change UserControl property from static class?

我在MainWindow.xaml中有Grid Grid充满了我的UserControl (修改后的Button )。

在静态类Globals中,我有布尔变量,在按Button会更改。 现在我还需要在此布尔变量更改上更改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;
            }

        }
    }

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

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" ... />

如果您未实现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);
    }
}

暂无
暂无

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

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