-2

I am using a piece of code that allows me to edit another window, e.g. a textbox located inside:

var MessageBox_Window = System.Windows.Application.Current.Windows.Cast<Window>().FirstOrDefault(window => window is MessageBoxWindow) as MessageBoxWindow;

I need to be able to change the contents of this window constantly however I cannot put the var in partial class, and if I put it anywhere else it is not global. If I was to use:

ProjectName.MessageBoxWindow MessageBox_Window = System.Windows.Application.Current.Windows.Cast<Window>().FirstOrDefault(window => window is MessageBoxWindow) as MessageBoxWindow;

in partial class, whenever I try to change the contents, I get a NullReferenceException.

Is there a way of making this code global so that it can be accessed from anywhere inside a window?

Nikolay Kostov
  • 16,433
  • 23
  • 85
  • 123
Callum Watkins
  • 2,844
  • 4
  • 29
  • 49
  • 4
    You shouldn't be trying to access the controls of another window from outside of that window. Let each window be responsible for managing its own internal controls. – Servy Jan 30 '15 at 18:52
  • 3
    Why would application requirements say anything about code needing to be accessible from every class in your application? That's not a business requirement at all. It's a technical implementation that may be used in the process of fulfilling a business requirement, and one that you should avoid using. Access the window from elsewhere, and have it do whatever you need it to do internally. – Servy Jan 30 '15 at 18:57
  • 1
    here is a good site you should read in regards to Accessing / Visibility [C# Basics Tutorial -Encapsulation](http://www.tutorialspoint.com/csharp/csharp_encapsulation.htm) – MethodMan Jan 30 '15 at 19:00
  • 1
    Why aren't you just using an event? Event gets fired, event gets caught by the windows UI thread via delegate, and makes the necessary update to window. This is what events are excel at. – StarPilot Jan 30 '15 at 19:14
  • good luck: https://msdn.microsoft.com/en-us/library/ms752347%28v=vs.110%29.asp – AK_ Jan 30 '15 at 19:22

2 Answers2

2

As Servy said, you shouldn't directly work with that window (and doing so from another Thread than the UI thread of that window is impossible).

Consider having a class that contains all the parameters you want to share. Your MessageBoxWindow is responsible for drawing itself based on those parameters, while other windows are free to change them.

MariusUt
  • 752
  • 4
  • 15
0

use a static class:

static class globalClass
{
    public static string globalData { get; set; }
}

and set it:

globalClass.globalData = "some value"
Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140
lem2802
  • 1,152
  • 7
  • 18