2015-08-03 60 views
0

我開發一個通用的Windows應用程序,當我將項目添加到列表框它不出差錯列表框項目添加的,而不是一次

這裏出現了兩次兩次是代碼

private async void btnNew_Click(object sender, RoutedEventArgs e) 
{ 
    listBox.Items.Add(nameBox.Text); 
    string type = comboBox.SelectedItem.ToString(); 
    URL url = new URL(); 
    url.type = type; 
    url.name = nameBox.Text; 
    url.info = infoBox.Text; 
    url.url = urlBox.Text; 
    url.isProtected = isProtectedSwitch.IsOn; 
    await url.saveToXML(); 
    infoBox.Text = ""; 
    nameBox.Text = ""; 
    urlBox.Text = ""; 
    comboBox.SelectedIndex = -1; 
} 

而且如果需要:

public async Task saveToXML() 
{ 
    //Directory.CreateDirectory(@"C:\Link"); 
    URL newURL = new URL(); 
    newURL.type = type; 
    newURL.name = name; 
    newURL.info = info; 
    newURL.url = url; 
    newURL.isProtected = isProtected; 
    newURL.amountOfClicks = amountOfClicks; 
    StorageFile file = await ApplicationData.Current.LocalFolder.CreateFileAsync(@"Link\" + newURL.name + ".xml", CreationCollisionOption.ReplaceExisting); 
    Stream fileStream = await file.OpenStreamForWriteAsync(); 
    DataContractSerializer serialize = new DataContractSerializer(typeof(URL)); 
    serialize.WriteObject(fileStream, newURL); 
} 
+0

你爲什麼要做所有事情兩次,要麼直接傳遞給saveToXML,要麼點擊 –

+0

這裏沒有任何東西可以添加項目兩次。你可能在'comboBox'的事件中有一些代碼嗎? – DavidG

+0

最簡單的解釋是您訂閱了此Click事件處理程序兩次。就像在XAML中一樣,再次在你的代碼中。 –

回答

1

在您提供的代碼中看不到任何問題。

在添加項目之前,您可能未清除退出listBox.Items。請確保您之前添加新項目列表listBox.Items.Clear()

0

在添加項目之前清理列表框。

listBox.Items.Clear(); 

這是可能的,你雙擊這個按鈕,所以代碼觸發兩次。

相關問題