Search code examples
wpfvb.netapplication-settingsmy.settings

How to access MyProject.MySettings.Default.SomeSetting from xaml?


I have defined a StringCollection in the Project Settings. I want to use the values in a ComboBox.

Is there a way to access it xamly?

I tried:

<CollectionViewSource Source="{x:Static src:MySettings.Default.MyCollection}" />
<CollectionViewSource 
    Source="{Binding Source={x:Static src:MySettings.Default.MyCollection}}" />

****src** is the xmlns of the project*

It says: "Type src:MySettings.Default was not found".

The thing is that MySettings is a class that offers a Default property which is a thread-safe instance of MySettings, I really want to get the collection from the Default property and not by instantiating a new on.

Is there other ways I am not aware of, maybe ObjectDataProvider can access static objects?

I thought, maybe I can make in the App.xaml a global resource that return MySettings.Default which is an instance of the MySettings class, and then access all its properties, I will try that out, but I prefer the easy way.


Solution

  • I've always done it using the x:Static Markup Extension. The key is to set the source to Settings.Default and the path to the desired setting like so:

    <Window x:Class="SettingsBindSample.Window1"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:s="clr-namespace:SettingsBindSample.Properties"
        Title="Window1" Height="300" Width="300">
        <Window.Resources>
            <CollectionViewSource x:Key="MyItems" 
          Source="{Binding MyCollection, Source={x:Static s:MySettings.Default}}" />
        </Window.Resources>
        <StackPanel>
            <ComboBox ItemsSource="{Binding Source={StaticResource MyItems}}" />
        </StackPanel>
    </Window>