Friday, December 17, 2010

WPF - Using Project Settings (Application / User Settings)

In this post, we will be discussing how we can use project properties in a WPF application. Specially, we will be considering how we can bind those properties to WPF elements.

Let us create a sample WPF application. We add a few settings to the project. In order to define settings, right click the startup project and select properties in Solution Explorer.

Now we define the settings. These settings might have different scopes. The available options are Application and User. An application properties is for all the user of the software. In case we updated a User setting, the update would just affect the current user.

It must be remembered that application wide settings are read-only. We can only change settings with user scope. In case we attempt to update the LabelText property defined above, it results in compile-time error.

Add a Window to the project. We add a few elements to the window as follows:

As you can see we have bound the Application setting LabelText to a Label label1. We also have a text box textBox1. We are binding the text of this TextBox to the user setting ManagerText. We are setting mode as TwoWay and copying the value to the actual setting as the user keep changing the text in the TextBox it is bound to. In order to prove that the setting is actually being updated, we are binding the same setting to another TextBlock. You will notice that as we keep typing in the TextBox, the TextBlock keeps itself updating. As the application keeps running, the application would be using the same value of the properties. If we want to persist it, we should be saving it. You can see that the button1_Click handler takes care of saving the settings.

WPF based development environment generally have a policy of no code-behind. Since Default is singleton, you can save it from anywhere from the application (including View Model). Now run the application, the application appears as follows (except the green boxes I drew in order to show you the bindng.

You can notice that the Label text is correctly updated with LabelText property. Now start typing in the second TextBox, you should notice that the same values keep appearing in the adjacent TextBlock. If we click "Update" button, the same values would appear when the application runs next time.

It would be a little different if we are developing application in VB.net. Instead of Binding through Project Properties, we need to bind it directly through MySettings.

Settings from Other Project:Generally a solution file contains many projects. It is possible that one project needs to access the settings from other project. In order to do that we need to set the Access Modifier of the settings as Public. It is available from top right when you open Project's properties in Visual Studio. Let's assume we need to access settings from other Project OtherProject. The name of property is SettingProperty.