我在MainWindow.xaml中有Grid
。 Grid
已填充UserControl
(修改后的Button
)。
在静态类Globals中,我有bool varible,它在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;
}
}
}
答案 0 :(得分:1)
您可以使用UserControl
方法获取Window.GetWindow
的父窗口的引用:
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
,您可以在x:Name
的XAML标记中为其MainWindow.xaml
:
<Grid x:Name="grid" ... />
答案 1 :(得分:0)
如果你没有实现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);
}
}