如何清除WPF列表框?

时间:2010-07-15 03:40:21

标签: c# 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()函数只返回数据作为列表,没有特殊的代码,如何解决这个问题。

5 个答案:

答案 0 :(得分:4)

获得此类行为的最佳方法是使用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”是x:XAML文件中根窗口的名称(你当然也可以使用像MVVM模式那样的datacontext:)

然后,如果您想在代码中添加/删除项目,只需直接访问该列表:

MyList.Clear();
MyList.Add("My New String");

当然,您还需要将集合的通用类型更改为您自己的类...

答案 1 :(得分:1)

您是否(通过直接添加到Items集合或仅通过ItemsSource填充ListBox?

如果是后者,请将ItemsSource设置为null并将其重新设置为重新加载。

答案 2 :(得分:1)

在您提供例外和其他详细信息之前,不能说明您的问题的原因是什么。但是建议做更好的方法。

  1. 让您的getnames方法返回IEnumerable。
  2. 构造一个ObservableCollection。
  3. 将ItemsSource设置为创建的ObservableCollection
  4. 现在您可以更改ObservableCollection以查看ListBox中的更改。

答案 3 :(得分:1)

在此之前:

  lstEntity.ItemsSource = sei.getNames();

清除列表框itemssource:

lstEntity.ItemsSource = "";

答案 4 :(得分:0)

如果您正在使用MVVM模式,请向ViewModel添加属性:

public IEnumerable Names {
    get { return sei.getNames() as IEnumerable; }
}

然后,在您的XAML中,将ItemsSource编码为:

<ListBox ... ItemsSource="{Binding Names}" ... />

每当Names列表的内容发生变化时,都会引发PropertyChanged事件;这将告诉WPF系统刷新ListBox:

PropertyChanged(this, new PropertyChangedEventArgs("Names");
相关问题