C# WPF 复选框的值为 null?

C# WPF Checkbox with null value?

提问人:Sebastian Southwell 提问时间:3/22/2019 最后编辑:Sebastian Southwell 更新时间:1/11/2020 访问量:1527

问:

我目前正在 WPF 中制作一个 GUI,并且正在开发一个旨在创建和配置消息室的页面,但下面的代码如下

else if (Password_Enabled.IsChecked == true && Password.Text.Length == 0)
        {
            return false; 
        }

出现错误

Password_Enabled.IsChecked“Password_Enabled.IsChecked”引发了“System.NullReferenceException”类型的异常

CheckBox 的 Xaml 如下所示

<CheckBox x:Name="Password_Enabled" IsChecked="False" Content="Password Enabled" HorizontalAlignment="Left" VerticalAlignment="Top" Checked="Password_Enabled_Checked" Unchecked="Password_Disabled_Checked" Margin="10,5,0,0" Grid.RowSpan="2"/>

我在网上搜索过,但是像这样的错误是标准化的,我知道这意味着该复选框被视为空。但是,虽然搜索我的代码没有找到任何说明原因的内容,但对此的任何帮助将不胜感激,谢谢。

编辑

我的页面 C# 的完整代码是

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace ChatRoom
{
   /// <summary>
   /// Interaction logic for New_Server.xaml
   /// </summary>
 public partial class New_Server : Page
{
    public New_Server()
    {
        InitializeComponent();
        Owner.Text = Global_Class.GetUsername(Environment.UserName);
    }
    public static string ChosenAddress = "";

    private bool CheckValidCredentials()
    {
        List<string> IllegalCharacters = new List<string>() { ",", "|", "\\", "/", ".", "?", "\"", "<", ">", ":" };
        bool Illegal = false;
        if (ServerName.Text.Length == 0)
        {
            return false;
        }
        foreach (string Check in IllegalCharacters)
        {
            if (ServerName.Text.Contains(Check))
            {
                Illegal = true;
                break;
            }
        }
        if (Illegal)
        {
            return false;
        }
        else if (Password_Enabled.IsChecked == true && Password.Text.Length == 0)
        {
            return false; 
        }
        else if (ChosenAddress == "")
        {
            return false; 
        }
        else
        {
            return true; 
        }
    }
    public void SetMakeServer()
    {
        if (CheckValidCredentials())
        {
            MakeServer.IsEnabled = true;
        }
        else
        {
            MakeServer.IsEnabled = false;
        }
    }
    private void Public_Server_Checked(object sender, RoutedEventArgs e)
    {
        MessageBox.Show("This Server Will Be Open to everyone in the College, Please Untick if you wish to change this.");
        CheckValidCredentials();
    }
    private void Password_Enabled_Checked(object sender, RoutedEventArgs e)
    {
        Password.IsEnabled = true;
        OneTimePass.IsEnabled = true;
        SetMakeServer();
    }
    private void Password_Disabled_Checked(object sender, RoutedEventArgs e)
    {
        Password.IsEnabled = false;
        OneTimePass.IsEnabled = false;
        SetMakeServer();
    }

    private void Back_Click(object sender, RoutedEventArgs e)
    {
        this.NavigationService.Navigate(new Server_Selection());
    }

    private void ServerDirectorySet_Click(object sender, RoutedEventArgs e)
    {
        using (var fbd = new System.Windows.Forms.FolderBrowserDialog())
        {
            System.Windows.Forms.DialogResult result = fbd.ShowDialog();
            if (result == System.Windows.Forms.DialogResult.OK)
            {
                ChosenAddress = fbd.SelectedPath;
                ServerDirectoryDisplay.Content = "Location: " + ChosenAddress;
            }
            else
            {
                ChosenAddress = "";
                SetMakeServer();
            }
        }
    }

    private void ServerName_TextChanged(object sender, TextChangedEventArgs e)
    {
        SetMakeServer();
    }

    private void Password_TextChanged(object sender, TextChangedEventArgs e)
    {
        SetMakeServer();
    }
}

}

C# WPF 复选框 NullReferenceException

评论

0赞 canton7 3/22/2019
在(从代码隐藏中的构造函数调用)完成运行之前运行该代码。InitializeComponent()
0赞 Sebastian Southwell 3/22/2019
@canton7 这也是我的想法,这是检查正确输入的函数的一部分,这是我用于 (Page) Main 函数的代码 tho 'public New_Server() { InitializeComponent();Owner.Text = Global_Class.GetUsername(Environment.用户名);}' 我什至没有调用该函数,它是由按钮引起的,但由于某种原因仍然表现得很奇怪。
0赞 canton7 3/22/2019
然后请发布您的完整代码 -- 最小的可重现示例
2赞 canton7 3/22/2019
右。我敢打赌,这是一个复选框,在构造时会选中它(在 InitializeComponent 中)。在注册之后检查,但在构造之前检查。因此,它确实会发生,因为在 InitializeComponent 完成运行之前运行。Public_ServerPublic_Server_CheckedPassword_EnabledPublic_Server_Checked
1赞 XAMlMAX 3/22/2019
当然,这里是第一名。

答:

3赞 Logan K 3/22/2019 #1

InitializeComponent 必须先完成,然后才能与 UI 上的任何内容进行交互。如果在 WPF 完成初始化之前尝试访问代码中的可视元素,则会收到 null 错误。

评论

1赞 Logan K 3/22/2019
我想这样可以把一些东西标记为答案,所以如果有人遇到这个,它就在那里。