如果您没有提供显示如何创建 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<System.String>" 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<System.String>" Scope="User">
<Value Profile="(Default)"><?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" /></Value>
</Setting>
每当您将项目添加到您的收藏设置时,列表框也会更新。