Forums - C# Corner

Forum guidelines
Evgenie Tivaniuk

Evgenie Tivaniuk

  • 1.5k
  • 17
  • 311

Accessing XAML from non-main class

Jun 19 2017 7:06 AM
I am making a video game. Some time ago, one person recommended me to use separate classes, and not have everything in one file. I did manage to separate some of functions and variables, but unfortunatelly, only those that don't affect xaml elements.
Mostly, xaml elements that change during game: label called "TextOutput", a few grids (each grid is a room) and a large number of images and buttons.
I will give an example, there is a door that can be opened.
So, the code for clicking on door:
  1. public void tmrHibernation1RightDoorOpening(object sender, EventArgs e)  
  2. {  
  3.     tmrDoorOpening.Stop();  
  5.     AreaTransition();  
  6.     ShowLockerRoom();  
  7.     areaLockerRoom.Visibility = Visibility.Visible;  
  8.     areaLockerRoom.IsEnabled = true;  
  9.     if (Resolution == "1600x900")  
  10.     areaLockerRoom.Margin = new Thickness(19, 31, 0, 0);  
  11.     if (Resolution == "1366x786")  
  12.     areaLockerRoom.Margin = new Thickness(16, 26, 0, 0);  
  13.     if (Resolution == "1024x768")  
  14.         areaLockerRoom.Margin = new Thickness(12, 27, 0, 0);     
  15.     if (Resolution == "1440x900")  
  16.         areaLockerRoom.Margin = new Thickness(17, 31, 0, 0);                  
  17. (Resolution == "1920x1080")               
  18.     areaLockerRoom.Margin = new Thickness(23, 38, 0, 0);   
  19.     if (Resolution == "800x600")  
  20.         areaLockerRoom.Margin = new Thickness(10, 20, 0, 0);                
  21.     ActionsReset();  
  22. }  
This works perfectly - in the main class. But if I try to move the void to another class, or even make a brand new void, that is supposed to change xaml elements, I get an error:
  1. An object reference is required for the nonstatic field, method, or property  
 I don't really understand how to bypass this. Xaml elements aren't static, and I already read that I shouldn't change them to be static, even if it's possible.
And if I create a variable of Button\Image\Grid etc, this will allow me to change their own attributes, not of those I need.
 I found out this article: 
It says about accessing controls from other FORMS - so I am not sure if it will work in my case, since I am using WPF, and not sure that this approach will avoid "object reference required" error.
What can be done to solve this?
Thank you in advance,

Answers (4)