2017-04-07 153 views
1

我创建WPF应用程序并在我的设置面板中有几个标签,文本框,组合框和两个按钮(保存)和(取消)。WPF - 组合框项目被复制

的XAML

<ComboBox x:Name="myCombobox" Grid.Column="1" Margin="18,372,4,0" VerticalAlignment="Top" Height="26" SelectionChanged="MyCombobox_SelectionChanged" /> 

我已经加入项目,我的组合框:

myCombobox.Items.Add("Test1"); 
myCombobox.Items.Add("Test2"); 
myCombobox.Items.Add("Test3"); 
foreach (var item in myCombobox.Items) 
    if (item.Equals(Properties.Settings.Default.MyCombobox)) 
     myCombobox.SelectedItem = item; 

,并添加SelectionChanged事件。这是它的外观:

private void MyCombobox_SelectionChanged(object sender, SelectionChangedEventArgs e) 
{ 
    if (myCombobox.SelectedItem.ToString().Equals("Test1")) 
    { 
     testGrid.Visibility = Visibility.Visible; 
    } 
    else if (myCombobox.SelectedItem.ToString().Equals("Test2") || myCombobox.SelectedItem.ToString().Equals("Test3")) 
    { 
     testGrid.Visibility = Visibility.Hidden; 
    } 
} 

当我点击取消按钮并重新启动我的设置面板我的组合框的项目是重复的。 (相同的值两次)。

我试图通过增加Cancel按钮单击事件

myCombobox.Items.Clear(); 

但此时另一个问题存在(myCombobox.SelectedItem为空),以防止这一点,我得到这个错误:

An exception of type 'System.NullReferenceException' occurred in IdentificationStation.exe but was not handled in user code

如何防止组合框项目被复制?或者我应该做其他的事情,有帮助吗?

+0

myCombobox.Items.Clear();将此添加到onchange事件中。 –

+1

你是如何填充你的组合?应该添加与该问题相关的代码。 – Anil

+0

该应用程序绝对在例程中调用了两次'myComboBox.Items.Add(...)'。这叫什么/如何?你能展示这种调用的方法吗? – Jegan

回答

1

你就不能避免

'System.NullReferenceException'

通过测试,如果myCombobox.SelectedItem是空的MyCombobox_SelectionChanged

private void MyCombobox_SelectionChanged(object sender, SelectionChangedEventArgs e) 
{ 
    if (myCombobox.SelectedItem != null) 
     if (myCombobox.SelectedItem.ToString().Equals("Test1")) 
     { 
      testGrid.Visibility = Visibility.Visible; 
     } 
     else if (myCombobox.SelectedItem.ToString().Equals("Test2") || myCombobox.SelectedItem.ToString().Equals("Test3")) 
     { 
      testGrid.Visibility = Visibility.Hidden; 
     } 
    } 
} 

我不认为这样做是不好的方式。

-2

使用此检查,以阻止另外的重复项:

if(!myComboBox.Items.Contains("item")) 
{ 
    myComboBox.Items.Add("item"); 
} 
+0

如果组合框被动态更新,您只需要进行这些类型的验证。对于像上面这样的静态更新,编码人员应该能够看到调用堆栈并修复例程,使其不会被调用两次。 – Jegan