Reputation: 1049
I have a ListBox (WPF) and I am adding to it strings at runtime.... If I try to add string that is already exists in the ListBox it throws me an exception..... telling that this item is already in the ListBox.... How can I add the same strings to ListBox ? Because I have situations in my application when I do have to add 2 identical strings.... thanks....
The ListBox -
<ListBox x:Name="listBox_MyListBox" Height="Auto" Width="Auto" Background="Transparent" MaxHeight="170" BorderThickness="0" Margin="3">
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Margin="3" Padding="2" Text="{Binding}" TextAlignment="Center" FontSize="13"/>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
in the code behind I add the string like that -
this.listBox_MyListBox.Items.Add(text.ToString());
Upvotes: 0
Views: 627
Reputation: 2587
Yes, you can add duplicate items to listbox, it allows without any issue Example:
private void Window_Loaded ( object sender, RoutedEventArgs e )
{
listBox_MyListBox.Items.Add ( "demo" );
listBox_MyListBox.Items.Add ( "demo" );
}
Note: It would not let you add duplicate if you are using any of data sources which dont allow duplicate: Dictionary or Hashtable may not allow duplicate entries, if that is the case with you then choose List or datatable as datasource
Upvotes: 0
Reputation: 22445
why not a simple list?
the easy not mvvm way:
public List<string> MyItems {get; set;}
listBox_MyListBox.ItemsSource = MyItems;
MyItems.Add("t1");
MyItems.Add("t2");
MyItems.Add("t1");//again
i would use a viewmodel with your list and bindging to the listbox. but the code above will work too.
Upvotes: 1