当我将此代码行添加到我的ComboBox选择事件中时,Initializecomponent将返回null引用



我的 InitializeComponent();行返回错误时,我将以下行添加到我的comboboxItem选择事件:

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");
        }
    }
}

我试图根据选择的组合构象来更改文本块的文本。

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">

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

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

相关内容

  • 没有找到相关文章

最新更新