当我将这行代码添加到我的ComboBox选择事件时,InitializeComponent返回一个空引用

时间:2018-02-19 11:55:51

标签: c# wpf

当我将以下行添加到我的ComboBoxItem Selection事件时,我的InitializeComponent();行返回错误:

namespace NewProject
{
    public partial class Page1 : Page
    {
        public Page1
        {
            InitializeComponent();
        }
        private void ComboBoxItem_Selected_1(object sender, RoutedEventArgs e) //same for ComboBoxItem_Selected_2,3
        {
            TextBlock_ComboBoxes.Text = ("Combo Box Number: 1");
        }
    }
}

我正在尝试根据选择的ComboBoxItem来更改TextBlock的文本。

XAML代码:

<ComboBox FontFamily="Arial" Grid.ColumnSpan="2">
    <ComboBoxItem Content="Combo Box Number 1" IsSelected="True" Selected="ComboBoxItem_Selected_1"/>
    <ComboBoxItem Content="Combo Box Number 2" Selected="ComboBoxItem_Selected_2"/>
    <ComboBoxItem Content="Combo Box Number 3" Selected="ComboBoxItem_Selected_3"/>
</ComboBox>
<TextBlock x:Name="TextBlock_ComboBoxes" Text="Combo Box Number: 1"/>

此Xaml代码包含在窗口内的框架内。这些是页面属性:

<Page x:Class="NewProject.Page1"
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
  xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
  mc:Ignorable="d" 
  d:DesignHeight="300" d:DesignWidth="600"
Title="Page 1">

1 个答案:

答案 0 :(得分:1)

InitializeComponent期间,可能会在TextBlock_ComboBoxes字段初始化之前触发SelectionChanged事件。您应该检查该字段是否为null

private void ComboBoxItem_Selected_1(object sender, RoutedEventArgs e)
{
    if (TextBlock_ComboBoxes != null)
    {
        TextBlock_ComboBoxes.Text = ("Combo Box Number: 1");
    }
}