2017-07-10 10 views
0

MainWindow.xamlにGridがあります。 Gridは私のUserControl(変更されたButton)で満たされています。静的クラスからUserControlプロパティを変更するには?

静的なクラスグローバルでは、私は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; 
      } 

     } 
    } 
+1

あなたのクリックの方法で背景を変更しないのはなぜ? –

+0

MVVMのパターン –

+1

に従うことを検討する必要があります.WPF 4.5以降、簡単に[静的プロパティにバインドする]ことができます(http://10rem.net/blog/2011/11/29/wpf-45-binding-and-change-notification -for-static-properties)を使用します。だから、単にグリッドの背景のためのDataTriggerを持つことができます。 – Clemens

答えて

1

UserControlの親ウィンドウへの参照は012を使用して取得できます方法:

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" ... /> 
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); 
    } 
} 
関連する問題