开发者

How do you store a WPF control value as a Property Setting in app.config?

We have a WPF windows application that contains a stackpanel control, that I want to be visible only for testing, but not when it is in production.

We'd like to store the visibility value of that stackpanel in the ap开发者_StackOverflow中文版plication configuration file (app.config).

What is the WPF way of achieving this?


First, you create your property in Visual Studio by going to the Project Properties/Settings and creating an Application-scope bool ShowMyStackPanel. This will automatically (1) create a Settings class in the Properties namespace and (2) add the following to your app.config:

<configuration>
    ...
    <applicationSettings>
        <CsWpfApplication1.Properties.Settings>
            <setting name="ShowMyStackPanel" serializeAs="String">
                <value>False</value>
            </setting>
        </CsWpfApplication1.Properties.Settings>
    </applicationSettings>
</configuration>

In your WPF window, you can now simply bind to Properties.Settings.Default.ShowMyStackPanel using a BooleanToVisibilityConverter:

<Window ...
    xmlns:prop="clr-namespace:CsWpfApplication1.Properties"
    ...>
    <Window.Resources>
        <BooleanToVisibilityConverter x:Key="MyBoolToVisibilityConverter" />
    </Window.Resources>
    ...
        <StackPanel Visibility="{Binding Source={x:Static prop:Settings.Default},
                                         Path=ShowMyStackPanel,
                                         Converter={StaticResource MyBoolToVisibilityConverter}}">
            ...
        </StackPanel>
    ...
</Window>


You could use the following markup extension to bind to the setting :

<StackPanel Visibility="{my:SettingBinding StackPanelVisibility}">
...

(assuming the setting is saved as a Visibility value (Visible/Collapsed/Hidden))

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜