C# 如何从静态类更改UserControl属性?
我在MainWindow.xaml中有网格。网格中填充了我的UserControl修改按钮 在静态类Globals中,我有bool变量,它在按下按钮时发生变化。现在我需要改变这个bool变量的网格背景颜色 问题是,除了MainWindow.xaml.cs代码落后之外,我无法从其他位置访问网格 Global.cs:C# 如何从静态类更改UserControl属性?,c#,wpf,xaml,user-controls,C#,Wpf,Xaml,User Controls,我在MainWindow.xaml中有网格。网格中填充了我的UserControl修改按钮 在静态类Globals中,我有bool变量,它在按下按钮时发生变化。现在我需要改变这个bool变量的网格背景颜色 问题是,除了MainWindow.xaml.cs代码落后之外,我无法从其他位置访问网格 Global.cs: public static class Globals { private static bool _player; public static
public static class Globals
{
private static bool _player;
public static bool Player {
get { return _player; }
set {
_player = value;
Debug.WriteLine(value);
}
}
}
我的用户控件:
如果您没有实现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父窗口的引用: 为了能够访问网格,您可以在MainWindow.XAML:
为什么不改变点击方法中的背景?你应该考虑遵循MVVM模式,因为WPF 4.5很容易。因此,您可以简单地为网格的背景设置一个DataTrigger。
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);
}
}
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="grid" ... />