Tuesday, March 31, 2009

DataBinding to App.Settings values

.Net 2.0 introduced this feature which helps to store and retrieve application specific settings very easily.You can easily create Settings through the visual editor.If we want to access them in code we can just use the Properties.Settings.Default object directly.The Default object will have all the properties which we had created at design time.
Showing ConnectionString entry in Messagebox
MessageBox.Show(Properties.Settings.Default.ConnectionString);


It is very easy.Lets learn how this can be binded in to a WPF TextBox.

First make a namespace reference to the Properties namespace.If your application name is WpfApplication1 it is xmlns:props=”WpfApplication1.Properties”.

Then in the Binding set source as the Default property available in the class Settings.Since it is static you have to use the x:Static binding extension.

Finally the path is ConnectionString which is the settings entry name.

Putting it altogether.


<Window
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Class="WpfApplication1.Window1"
x:Name="Window"
xmlns:props="clr-namespace:WpfApplication1.Properties">
<Grid x:Name="LayoutRoot">
<TextBox  HorizontalAlignment="Left"  VerticalAlignment="Top"
Text="{Binding Source={x:Static props:Settings.Default},Path=ConnectionString}">
</TextBox>
</Grid>
</Window>


So enjoy WPF data binding to Properties.Settings.Default.

No comments:

Post a Comment