尝试在WPF应用程序中隐藏文本块时获取null异常

时间:2013-02-19 12:45:00

标签: c# wpf exception null visibility

我正在尝试开发一些工具,因为我是WPF的新手。我有一个有两个项目的组合框。

xaml代码如下

<Window x:Class="New_generator2.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Window1" Height="500" Width="500">
    <Grid>

        <ComboBox Height="21" Margin="36,15,22,0" Name="comboBox1" VerticalAlignment="Top" AllowDrop="True" Text="" SelectionChanged="comboBox1_SelectionChanged">
            <ComboBoxItem Tag="1" IsSelected="True" Name="ComboBox_Rule_Parameter">Rule_Parameter</ComboBoxItem>
            <ComboBoxItem Tag="2" Name="ComboBox_Rule_Instance">Rule_Instance</ComboBoxItem>
        </ComboBox>

        <TextBox Height="25" HorizontalAlignment="Right" Margin="0,71,14,0" Name="Field_Code_textbox" VerticalAlignment="Top" Width="220"  Visibility="Hidden" />
        <TextBlock Height="25" HorizontalAlignment="Left" Margin="14,73,0,0"  Name="Field_Code" VerticalAlignment="Top" Width="220" TextBlock.FontSize="20" Background="BurlyWood" TextAlignment="Center"  Text="Data_Field_Code" Visibility="Hidden"/>
        <TextBox Height="84" Margin="35,0,23,12" Name="Script" VerticalAlignment="Bottom" Width="420" Visibility="Hidden"/>
        <Button Height="25" Margin="120,0,123,106" Name="Generate" VerticalAlignment="Bottom" TextBlock.FontSize="18" Background="BlanchedAlmond" TextBlock.TextAlignment="Justify" Click="button1_Click" Visibility="Hidden">Dispaly</Button>

    </Grid>
</Window>

C#代码如下

public partial class Window1 : Window
    {
        public Window1()
        {
            InitializeComponent();
            Field_Code = new TextBlock();
        }

        private void comboBox1_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (comboBox1.SelectedIndex == 0)
            {
                Field_Code.Visibility = Visibility.Visible;
            }
            if (comboBox1.SelectedIndex == 1)
            {
                Field_Code.Visibility = Visibility.Hidden;
            }
        }

        private void button1_Click(object sender, RoutedEventArgs e)
        {
            Script.Text = Field_Code_textbox.Text;
        }
    }

当我运行它时,我得到一个Null Exception,即对象引用未设置为对象的实例。我附上了null异常的屏幕截图。

enter image description here

请帮我解决这个问题。

4 个答案:

答案 0 :(得分:2)

在构造函数中将Field_Code的初始化移动到BEFORE InitialiseComponent()。

答案 1 :(得分:1)

这是因为从InitializeComponent()调用了combobox_selection更改,此时Field_Code未初始化。最简单的解决方法是在Window1()构造函数中将Field_Code = new TextBlock();移到InitializeComponent();之前。

答案 2 :(得分:0)

看起来更改的组合选择是从InitializeComponent触发的。

答案 3 :(得分:0)

就个人而言,我会创建一个像public bool FieldCodeVisible { .. }这样的属性,并将文本框的可见性绑定到该属性。

您可以说Field_Code.Visibility = Visibility.Visible;

而不是FieldCodeVisible = true;

这样您就可以在ViewModel中使用逻辑,但您可以在视图中决定功能