有没有办法通过不删除和添加 ItemsSource 来更新 ListBox 的项目?
Is there any way to update the Items of a ListBox by not removing and adding the ItemsSource?
我正在将项目添加到我的列表框中,但无论何时我想添加它们,我都需要删除并添加新的项目源,有什么方法可以使列表框自动更新,这样我就不需要删除和添加 ItemsSource 了吗?谢谢!
我目前正在使用 ObservableCollection。
您可以使用数据绑定绑定到该集合,然后让列表框根据其中的任何内容自动填充。这将是一个带有“wow”作为文本的勾选复选框的列表框,无论集合中有多少。
<ListBox Name="testList" ItemsSource="{Binding CollectionName}" >
<ListBox.ItemTemplate>
<DataTemplate>
<CheckBox IsChecked="true">
<TextBlock Text="{Binding Content}"/>
</CheckBox>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
public class ItemInCollection
{
public string Content = "wow";
}
我认为您误解了 Observable Collection
的概念,因为它提供了您需要的功能。
Observable 集合已经内置了刷新 UI 等功能,这意味着当您从代码隐藏或 ViewModel 更新集合时,UI 也会更新。
有用link:What is the use of ObservableCollection in .net?
我正在将项目添加到我的列表框中,但无论何时我想添加它们,我都需要删除并添加新的项目源,有什么方法可以使列表框自动更新,这样我就不需要删除和添加 ItemsSource 了吗?谢谢!
我目前正在使用 ObservableCollection。
您可以使用数据绑定绑定到该集合,然后让列表框根据其中的任何内容自动填充。这将是一个带有“wow”作为文本的勾选复选框的列表框,无论集合中有多少。
<ListBox Name="testList" ItemsSource="{Binding CollectionName}" >
<ListBox.ItemTemplate>
<DataTemplate>
<CheckBox IsChecked="true">
<TextBlock Text="{Binding Content}"/>
</CheckBox>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
public class ItemInCollection
{
public string Content = "wow";
}
我认为您误解了 Observable Collection
的概念,因为它提供了您需要的功能。
Observable 集合已经内置了刷新 UI 等功能,这意味着当您从代码隐藏或 ViewModel 更新集合时,UI 也会更新。
有用link:What is the use of ObservableCollection in .net?