【问题标题】:Refresh wpf listbox when collection changes集合更改时刷新 wpf 列表框
【发布时间】:2018-04-28 20:45:16
【问题描述】:

我正在使用带有字符串集合的设置。

我使用以下绑定填充列表框:

ItemsSource="{Binding QuadStash, Source={StaticResource Settings}, Mode=TwoWay}"

当我向集合中添加新字符串时,列表框中的项目不会更新。

我错过了什么?

【问题讨论】:

  • 你能显示后面的代码吗?
  • 这就是我添加新 Settings.Default.Collection.Add("STRING"); Settings.Default.Save();

标签: c# wpf listbox


【解决方案1】:

如果您没有提供显示如何创建 StaticResource 的代码,我将假设您希望直接从 xaml 绑定设置。

从 XAML 绑定 Settings.Default

在第一个实例中,添加指向声明设置类的命名空间的 XML 命名空间:

xmlns:properties="clr-namespace:WpfSettings.Properties"

然后您可以从设置中绑定您的集合,如下所示:

ItemsSource="{Binding Source={x:Static properties:Settings.Default}, Path=Collection}"

由于您直接绑定到设置中直接声明的集合,因此如果 WPF 未实现 INotifyCollectionChanged,则它不会意识到集合更新。要解决这个问题,您可以在设置中创建ObservableCollection

在设置中创建 ObservableCollection

Open settings in XML editor 并添加新设置如下:

<Setting Name="Collection" Type="System.Collections.ObjectModel.ObservableCollection&lt;System.String&gt;" Scope="User">
  <Value Profile="(Default)" />
</Setting>

然后在设置编辑器中添加默认值(source):

<?xml version="1.0" encoding="utf-16"?>
<ArrayOfString xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
               xmlns:xsd="http://www.w3.org/2001/XMLSchema" />

最后可能是这样的:

<Setting Name="Collection" Type="System.Collections.ObjectModel.ObservableCollection&lt;System.String&gt;" Scope="User">
  <Value Profile="(Default)">&lt;?xml version="1.0" encoding="utf-16"?&gt;
&lt;ArrayOfString xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
            xmlns:xsd="http://www.w3.org/2001/XMLSchema" /&gt;</Value>
</Setting>

每当您将项目添加到您的收藏设置时,列表框也会更新。

【讨论】:

  • 非常感谢维塔利。很好的解释。 :)
猜你喜欢
  • 2013-11-03
  • 1970-01-01
  • 1970-01-01
  • 2012-11-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-01-09
  • 2012-06-14
相关资源
最近更新 更多