我正在尝试创建一个纯代码 WPF 应用程序,但是当我在文本框中键入时出现上述错误。这是虽然我的所有变量都已初始化。
windows1.xaml 是这样的:
<?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>
后面的代码是这样的:
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;
}
}
}
这个新手根本不知道做错了什么,非常感谢任何帮助。谢谢大家。