将WPF属性绑定到C#中的ApplicationSettings的最佳方法?

时间:2020-03-06 14:56:29  来源:igfitidea点击:

将WPF属性绑定到C#中的ApplicationSettings的最佳方法是什么?是否有Windows窗体应用程序中的自动方式?与此问题类似,我们如何(也可能)在WPF中执行相同的操作?

解决方案

Kris,我不确定这是绑定ApplicationSettings的最佳方法,但这就是我在Witty中做到的方式。

1)在窗口/页面/用户控件/容器中为要绑定的设置创建一个依赖项属性。这是我有一个用户设置来播放声音的情况。

public bool PlaySounds
    {
        get { return (bool)GetValue(PlaySoundsProperty); }
        set { SetValue(PlaySoundsProperty, value); }
    }

    public static readonly DependencyProperty PlaySoundsProperty =
        DependencyProperty.Register("PlaySounds", typeof(bool), typeof(Options),
        new FrameworkPropertyMetadata(false, new PropertyChangedCallback(OnPlaySoundsChanged)));

    private static void OnPlaySoundsChanged(DependencyObject obj, DependencyPropertyChangedEventArgs args)
    {
        Properties.Settings.Default.PlaySounds = (bool)args.NewValue;
        Properties.Settings.Default.Save();
    }

2)在构造函数中,初始化属性值以匹配应用程序设置

PlaySounds = Properties.Settings.Default.PlaySounds;

3)在XAML中绑定属性

<CheckBox Content="Play Sounds on new Tweets" x:Name="PlaySoundsCheckBox" IsChecked="{Binding Path=PlaySounds, ElementName=Window, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />

我们可以下载完整的Witty源代码以查看其实际效果,或者仅浏览选项窗口的代码。

另请阅读这篇有关在BabySmash中如何完成操作的文章

仅在需要更改通知时,才需要使用DO来支持"设置"(例如Alan的示例)!绑定到POCO设置类也将起作用!

最简单的方法是绑定到一个将应用程序设置公开为属性的对象,或者将该对象作为StaticResource包含并绑定到该对象。

我们可以采取的另一个方向是创建自己的标记扩展,因此我们可以简单地使用PropertyName =" {ApplicationSetting SomeSettingName}"。要创建自定义标记扩展,我们需要继承MarkupExtension并使用MarkupExtensionReturnType属性装饰该类。 John Bowen撰写了有关创建自定义MarkupExtension的文章,该文章可能会使过程更加清晰。

我们可以直接绑定到Visual Studio创建的静态对象。

在Windows声明中添加:

xmlns:p="clr-namespace:UserSettings.Properties"

其中" UserSettings"是应用程序名称空间。

然后,我们可以将绑定添加到正确的设置:

<TextBlock Height="{Binding Source={x:Static p:Settings.Default}, 
           Path=Height, Mode=TwoWay}" ....... />

现在,我们可以保存设置,例如在关闭应用程序时:

protected override void OnClosing(System.ComponentModel.CancelEventArgs e)
{
    Properties.Settings.Default.Save();
    base.OnClosing(e); 
}

我喜欢接受的答案,但是遇到了一个特殊情况。我将文本框设置为"只读",这样我只能在代码中更改其值。尽管我将模式设置为" TwoWay",但我不明白为什么该值未传播回"设置"。

然后,我发现了这一点:http://msdn.microsoft.com/en-us/library/system.windows.data.binding.updatesourcetrigger.aspx

The default is Default, which returns the default UpdateSourceTrigger value of the target dependency property. However, the default value for most dependency properties is PropertyChanged, while the Text property has a default value of LostFocus.

因此,如果文本框具有IsReadOnly =" True"属性,则必须向Binding语句添加UpdateSourceTrigger = PropertyChanged值:

<TextBox Text={Binding Source={x:Static p:Settings.Default}, Path=myTextSetting, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged} ... />