文本框显示为空WPF



我有3个文本框,用户可以修改它们来改变窗口某些颜色的RGB颜色。我要给他们一个可视化的效果就是在文本框旁边有一个框显示他们用文本框中的RGB值制作的颜色。为此,我将所有3个文本框的TextChanged事件设置为一个方法,该方法从3个文本框中获取文本,使用TryParse将其转换为整数,将数字分配给画笔,然后将画笔分配给框,以便用户可以看到它。XAML看起来像这样:

<TextBox Name="ColorPickerDisplayRed" Background="Transparent"
BorderBrush="Transparent"
FontFamily="Moon 2.0"
Foreground="#6BAAFF"
Text="255"
TextAlignment="Center"
Margin="0, -1.2, 0, 0"
TextChanged="UpdateColorPickerDisplay"/>

我复制并粘贴了绿色和蓝色,所以除了文本框的名称之外,一切都是一样的。然后,为了得到整数值,我这样写:

private void UpdateColorPickerDisplay(object sender, TextChangedEventArgs e)
{
int R;
int G;
int B;
if (int.TryParse(ColorPickerDisplayRed.Text, out R)) ;
if (int.TryParse(ColorPickerDisplayGreen.Text, out G)) ;
if (int.TryParse(ColorPickerDisplayBlue.Text, out B)) ;
var brush = new SolidColorBrush(Color.FromArgb(255, (byte)R, (byte)G, (byte)B));
ColorPickerDisplay.Background = brush;
}

但是当我运行它时,我得到一个错误,说&;ColorPickerDisplayGreen是null。&;然后我试着为每个框设置文本作为测试,得到了同样的错误。我尝试了所有3个文本框,它只适用于红色。是因为我从所有3个文本框调用相同的方法吗?

解决了,不知道TextChanged被立即调用了

添加?在访问文本属性&它将修复这个问题

int R;
int G;
int B;
if (int.TryParse(ColorPickerDisplayRed?.Text, out R)) ;
if (int.TryParse(ColorPickerDisplayGreen1?.Text, out G)) ;
if (int.TryParse(ColorPickerDisplayBlue?.Text, out B)) ;
var brush = new SolidColorBrush(Color.FromArgb(255, (byte)R, (byte)G, (byte)B));
ColorPickerDisplayRed.Background = brush;

最新更新