I am a NOVICE and am very much struggling with what seems should be a very simple task. How do I modify a property of a MainWindow
TextBlock
, from ano
Basically there are more than 2-3 methods. Given method is quite easier to understand & handle. You can access MainWindow controls by following codes (1),(2),(3),(4).
In File: MainWindow.xaml.cs
public partial class MainWindow
{
internal static MainWindow Main; //(1) Declare object as static
public MainWindow()
{
InitializeComponent();
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
Main =this; //(2) Defined Main (IMP)
var AnyClassORWindow=new Class1(); //Initialize another Class
AnyClassORWindow.ShowValue();
}
}
In File: Class1.cs
internal class Class1 : MainWindow //(3) Inherited
{
internal void Display()
{
MessageBox.Show(Main.TextBox1.Text); //(4) Access MainWindow Controls by adding 'Main' before it.
}
}
Notes:-
- It's good practice to use code (2) after window LOADED not in CONSTRUCTOR.
- Code (2) in constructor may leave run-time problems.
- Another simple method is to use 'ref MainWindow_field' by passing to each class's Constructor OR assign '(MainWindow) Application.Current.MainWindow' to static Main.