I am trying to create a code-only WPF app but am getting the above error when I type in the textBox. This is though ALL my variables are initialized.
The windows1.xaml is this:
<?xml version="1.0" encoding="utf-8"?>
<Window>
x:Class="BlendCatalogue.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="BlendCatalogue"
Height="300"
Width="300">
</Window>
The code behind is this:
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
namespace BlendCatalogue
{
public partial class Window1 : Window
{
private TextBlock textBlock;
private TextBox textBox;
public Window1()
{
InitializeComponent();
Initialization();
}
public void Initialization()
{
this.Width=300;
this.Height=200;
this.Background =Brushes.Aquamarine;
this.Title = "Only the best!";
Grid layoutGrid = new Grid();
StackPanel stackpanel = new StackPanel();
layoutGrid.Children.Add(stackpanel);
this.AddChild(layoutGrid);
TextBlock textBlock = new TextBlock();
textBlock.Margin = new Thickness(6);
textBlock.Height = 20;
textBlock.TextAlignment = TextAlignment.Center;
textBlock.Text = "Hello my World!";
stackpanel.Children.Add(textBlock);
TextBox textBox = new TextBox();
textBox.Margin = new Thickness(5);
textBox.Width = 150;
textBox.TextAlignment = TextAlignment.Center;
textBox.Text = "";
textBox.TextChanged += OnTextChanged;
stackpanel.Children.Add(textBox);
Button btnColor = new Button();
btnColor.Margin = new Thickness(5);
btnColor.Width = 150;
btnColor.Content = "Change Text Color";
btnColor.Click += btnChangeColor_Click;
stackpanel.Children.Add(btnColor);
Button btnSize = new Button();
btnSize.Margin = new Thickness(5);
btnSize.Width = 150;
btnSize.Content = "Change Text Color";
btnSize.Click += btnChangeSize_Click;
stackpanel.Children.Add(btnSize);
}
private void OnTextChanged(object sender, TextChangedEventArgs e)
{
textBlock.Text = textBox.Text;
}
private void btnChangeColor_Click(object sender, RoutedEventArgs e)
{
if (textBlock.Foreground == Brushes.Black)
textBlock.Foreground = Brushes.Red;
else
textBlock.Foreground = Brushes.Black;
}
private void btnChangeSize_Click(object sender, RoutedEventArgs e)
{
if (textBlock.FontSize == 11)
textBlock.FontSize = 42;
else
textBlock.FontSize = 11;
}
}
}
This newbie simply does not know what is being done wrong and would really appreciate any help.
Thanks all.
Your are creating two
TextBlock'sand twoTextBox'sone with Module level scope and one with Local scope. You then initialize the one with Local scope and try to use the one with Module level scope causing your error.Try changing your code in your Initialization Method to: