简体   繁体   English

列表框-添加两个相同的项目-WPF

[英]Listbox - add two identical items - WPF

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 ? 我有一个ListBox(WPF),正在运行时向其添加字符串....如果我尝试添加ListBox中已经存在的字符串,则会引发异常.....告知该项目已存在ListBox...。如何将相同的字符串添加到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());

why not a simple list? 为什么没有简单的清单?

the easy not mvvm way: 简单而不是mvvm的方式:

 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. 我会在您的列表中使用ViewModel并绑定到列表框。 but the code above will work too. 但是上面的代码也可以。

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 注意:如果您使用不允许重复的任何数据源,则不允许添加重复:Dictionary或Hashtable可能不允许重复条目,如果是这种情况,则选择List或datatable作为数据源

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

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