【问题标题】:Textbox showing as null WPF显示为空 WPF 的文本框
【发布时间】:2021-10-12 05:58:05
【问题描述】:

我有 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 为空。”。然后我尝试将每个框的文本设置为测试并得到相同的错误。我对所有 3 个文本框都进行了尝试,但它只对红色有效。是因为我从所有 3 个文本框中调用了相同的方法吗?

已解决,不知道 TextChanged 是否立即被调用。

【问题讨论】:

  • 这可能是TextChanged 事件的副作用。它在其他文本框被实例化之前被触发。如果您想使用事件管理文本框,请注意在事件处理程序的开头放置一个标志,以便不会处理所有不需要的事件(过早触发)。一旦表单完全加载,清除标志,并强制初始化文本框。
  • 您是否尝试过在其上放置断点以便查看事件何时被调用?

标签: c# wpf xaml


【解决方案1】:

添加?在访问 Text 属性之前,它将解决问题

            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;

【讨论】:

    猜你喜欢
    • 2017-02-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-10
    • 1970-01-01
    • 1970-01-01
    • 2011-07-20
    • 1970-01-01
    相关资源
    最近更新 更多