2012-02-12 26 views
8

मेरी XAML फाइल उपयोग करने से पहले रिक्त होना ही चाहिएत्रुटि: आइटम संग्रह ItemsSource

<ListBox Height="522" HorizontalAlignment="Left" Margin="20,162,0,0" Name="listBox1" VerticalAlignment="Top" Width="448" ItemsSource="{Binding}"> 
    <ListBox.ItemTemplate> 
     <DataTemplate> 
      <StackPanel Orientation="Horizontal"> 
       <TextBlock Text="{Binding Text}" Foreground="#FFC8AB14" FontSize="36" /> 
      </StackPanel> 
     </DataTemplate> 
    </ListBox.ItemTemplate> 
</ListBox> 

xaml.cs फ़ाइल

 listBox1.Items.Clear(); 
     for (int i = 0; i < tasks.Count(); i++) { 
      List<Taskonlistbox> dataSource = new List<Taskonlistbox>(); 
      dataSource.Add(new Taskonlistbox() {Text = "Blalalalala"}); 
      this.listBox1.ItemsSource = dataSource; // visual stdio shows error here: 
     } 

Taskonlistbox:

public class Taskonlistbox 
{ 
    public string Text { get; set; } 
} 

त्रुटि: "आइटम संग्रह आइटम्ससोर्स का उपयोग करने से पहले खाली होना चाहिए " कोई समस्या क्या है?

+1

यह http://stackoverflow.com/questions/683863/wpf-items-collection-must से संबंधित लगता है बना सकते हैं और आवंटित -बे-रिक्त-पहले-उपयोग-आइटम्ससोर्स – Chriseyre2000

+0

शायद रूट त्रुटि नहीं है लेकिन आपको आइटम्ससोर्स को फॉर-लूप के अंदर सेट नहीं करना चाहिए। –

उत्तर

13

आप केवल एक बार सूची बनाना चाहते हैं और केवल एक बार डेटा स्रोत असाइन करना चाहते हैं! इसलिए, सूची से पहले पाश डेटा स्रोत के बाद पाश

// Clear the listbox. 
// If you never add items with listBox1.Items.Add(item); you can drop this statement. 
listBox1.Items.Clear(); 

// Create the list once. 
List<Taskonlistbox> dataSource = new List<Taskonlistbox>(); 

// Loop through the tasks and add items to the list. 
for (int i = 0; i < tasks.Count(); i++) { 
    dataSource.Add(new Taskonlistbox {Text = "Blalalalala"}); 
} 

// Assign the list to the `ItemsSouce` of the listbox once. 
this.listBox1.ItemsSource = dataSource; 
+0

आपको बहुत बहुत धन्यवाद! – tbsasa

संबंधित मुद्दे