For better or worse, I am building a WPF UI in code behind only. I have a button and a Text block within a Stack Panel. The button, upon clicking, updates the TextBlock with some information. If I make the TextBlock a member of the class, it will work successfully. However, just declaring global UI elements all over the place feels like the easy way out. Is there a way to instantiate the TextBlock in the MainWindow() and still have access to it in the button click Event?
The following pseudo code works:
public partial class MainWindow : Window
{
public TextBlock myTextBlock;
public MainWindow()
{
StackPanel mainStackPanel = new StackPanel();
Button myButton = new Button();
myButton.Click += NewButton_Click();
mainStackPanel.Children.Add(myTextBlock);
mainStackPanel.Children.Add(myButton);
Content = mainStackPanel;
}
private void NewGridButton_Click(object sender, RoutedEventArgs e)
{
myTextBlock.Text = "Some Text"
}
}
However, I am curious if something along these lines is also possible:
public partial class MainWindow : Window```
{
public MainWindow()
{
StackPanel mainStackPanel = new StackPanel();
Button myButton = new Button();
TextBlock myTextBlock = New TextBlock();
myButton.Click += NewButton_Click();
mainStackPanel.Children.Add(myTextBlock);
mainStackPanel.Children.Add(myButton);
Content = mainStackPanel;
}
private void NewGridButton_Click(object sender, RoutedEventArgs e)
{
//Somehow Access the myTextBlock from MainWindow here in order to set the text?
myTextBlock.Text = "Some Text" // This would not compile.
}
}
For brevity, the code here is just for example and not fully functional. Thank you in advance for any information you may be able to share on this topic.
EDIT - Follow up. The consensus from the answers here seem to indicate I was overthinking this issue. A private class variable that represents the UI element I wish to use seems to be a universally accepted (and not necessarily a lazy) way to declare and access your UI elements. Thanks to everyone who took the time to review and comment.