[英]How to clear WPF listbox?
Hai正在使用wpf列表框,调用重载数据功能时无法清除列表,我只想在运行时重载新数据,而页面加载时它会正确加载数据,刷新时会提取新数据itemsource我可以在调试模式下看到它,但是列表框中没有新数据,旧数据仍保留在列表中,我什至无法清除,当我调用list.items.clear()时,它会引发异常和应用程序崩溃,我尝试了很多方法,是我的XAML绑定中的任何问题,以下是我的代码。
<DataTemplate x:Key="listBoxTemplate">
<StackPanel Margin="3">
<DockPanel >
<TextBlock FontWeight="Bold" Text="{Binding Name}" DockPanel.Dock="Left" Margin="5,0,10,0"/>
<TextBlock Text=" " />
<TextBlock Text="{Binding Percnt}" Foreground="Green" FontWeight="Bold" />
</DockPanel>
</StackPanel>
</DataTemplate>
我的清单
<ListBox Height="898" Name="lstEntity" Width="291" ItemTemplate="{StaticResource listBoxTemplate}" SelectionChanged="lstEntity_SelectionChanged"/>
绑定码
lstEntity.ItemsSource = sei.getNames();
getNames()函数仅将数据作为列表返回,其中没有任何特殊代码,如何解决此问题。
获得这种行为的最好方法是使用DependencyProperty和绑定。
在类文件中创建DP,如下所示:
#region MyList dependency property
public static readonly DependencyProperty MyListProperty = DependencyProperty.Register("MyList", typeof(ObservableCollection<String>), typeof(Window1));
public ObservableCollection<String> MyList
{
get { return (ObservableCollection<String>) GetValue(MyListProperty); }
set { SetValue(MyListProperty, value); }
}
#endregion
然后在您的XAML中像这样绑定到该DP:
<ListBox ItemSource={Binding Path=MyList, ElementName=MyWindow} Height="898" Name="lstEntity" Width="291" ItemTemplate="{StaticResource listBoxTemplate}" SelectionChanged="lstEntity_SelectionChanged"/>
其中,“ MyWindow”是XAML文件中根窗口的x:Name(当然,您也可以使用数据上下文,例如MVVM模式:)
然后,如果要从代码中添加/删除项目,只需直接访问列表:
MyList.Clear();
MyList.Add("My New String");
当然,您还需要将集合的通用类型更改为您自己的类...
您是否曾经通过直接添加到Items集合或仅通过ItemsSource填充ListBox?
如果是后者,则将ItemsSource设置为null并将其设置为重新加载。
在您提供例外情况和其他详细信息之前,您无法说出您的案子是什么原因。 但是建议做某事的更好方法。
getnames
方法返回IEnumerable。 现在,您可以更改ObservableCollection,以查看ListBox中的更改。
在您这样做之前:
lstEntity.ItemsSource = sei.getNames();
清除列表框itemssource:
lstEntity.ItemsSource = "";
如果使用的是MVVM模式,请向ViewModel中添加一个属性:
public IEnumerable Names {
get { return sei.getNames() as IEnumerable; }
}
然后,在您的XAML中,将ItemsSource编写为:
<ListBox ... ItemsSource="{Binding Names}" ... />
每当“名称”列表的内容发生更改时,都将引发PropertyChanged事件; 这将告诉WPF系统刷新您的ListBox:
PropertyChanged(this, new PropertyChangedEventArgs("Names");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.