简体   繁体   English

WPF C# 组合框默认值

[英]WPF C# Combox default value

I have a problem with the set of a default value for a combobox:我对 combobox 的默认值集有疑问:

<ComboBox x:Name="cmbAuthentification" Height="20" Grid.Row="1" Grid.Column="1" BorderBrush="#FF2BBFF0" FontFamily="Segoe UI Light" IsReadOnly="True" SelectionChanged="cmbAuthentification_SelectionChanged">
    <ComboBoxItem>Windows</ComboBoxItem>
    <ComboBoxItem>SQL Server</ComboBoxItem>
</ComboBox>

In the xmal, I have this code:在 xmal 中,我有以下代码:

private void cmbAuthentification_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    if (cmbAuthentification.SelectedIndex == 0)
    {
        txtUserID.IsEnabled = false;
        txtUserID.Clear();
        txtUserPwd.IsEnabled = false;
        txtUserPwd.Clear();
    }

    if (cmbAuthentification.SelectedIndex == 1)
    {
        txtUserID.IsEnabled = true;
        txtUserPwd.IsEnabled = true;
    }
}

When I try to set SelectedIndex="0" in the ComboBox, I have an error at runtime: NullReferenceException : Object reference not set to an instance of an object.当我尝试在 ComboBox 中设置 SelectedIndex="0" 时,运行时出现错误:NullReferenceException : Object 引用未设置为 ZA8CFDE6331BD59EB2AC96F8911C4B6666

Your issue is that the controls haven't yet been loaded when your event handler is executed for the first time.您的问题是第一次执行事件处理程序时尚未加载控件。

You could check whether the value of the IsLoaded and hook up to the Loaded event if it returns false :您可以检查IsLoaded的值是否返回false并连接到Loaded事件:

private void cmbAuthentification_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    if (!cmbAuthentification.IsLoaded)
    {
        cmbAuthentification.Loaded += (ss, ee) => cmbAuthentification_SelectionChanged(sender, e);
        return;
    }

    if (cmbAuthentification.SelectedIndex == 0)
    {
        txtUserID.IsEnabled = false;
        txtUserID.Clear();
        txtUserPwd.IsEnabled = false;
        txtUserPwd.Clear();
    }

    if (cmbAuthentification.SelectedIndex == 1)
    {
        txtUserID.IsEnabled = true;
        txtUserPwd.IsEnabled = true;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM