gpt4 book ai didi

c# - 如何清除 WPF 列表框?

转载 作者:太空狗 更新时间:2023-10-30 00:46:28 24 4
gpt4 key购买 nike

Hai 我正在使用 wpf 列表框,我在调用重新加载数据函数时无法清除列表,我只想在运行时重新加载新数据,而页面加载时它会正确加载数据,当我刷新新数据时在项目源中获取我可以在 Debug模式下看到,但列表框中没有新数据,旧数据保留在列表中,我什至无法清除,当我调用 list.items.clear() 时,它会抛出异常和应用程序崩溃,我尝试了很多方法,我的 XAML 绑定(bind)是否有问题,以下是我的代码。

<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"/>

绑定(bind)代码

   lstEntity.ItemsSource = sei.getNames();

getNames() 函数只是将数据作为列表返回,其中没有任何特殊代码,如何解决这个问题。

最佳答案

获得此类行为的最佳方法是使用 DependencyProperty 和绑定(bind)。

在你的类文件中像这样创建 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 中像这样绑定(bind)到该 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");

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

关于c# - 如何清除 WPF 列表框?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3252287/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com