82

在 WPF 中,我可以对设置中定义的值使用绑定吗?如果可以,请提供样品。

4

4 回答 4

141

首先,您需要添加一个自定义 XML 命名空间,该命名空间将设计定义设置的命名空间:

xmlns:properties="clr-namespace:TestSettings.Properties"

然后,在您的 XAML 文件中,使用以下语法访问默认设置实例:

{x:Static properties:Settings.Default}

所以这是最终的结果代码:

<ListBox x:Name="lb"
         ItemsSource="{Binding Source={x:Static properties:Settings.Default},
                               Path=Names}" />

来源:WPF - 如何将控件绑定到设置中定义的属性?


注意:正如@Daniel 和@nabulke 所指出的,不要忘记将设置文件的访问修饰符Public设置为和范围设置为User

于 2009-05-10T09:57:18.203 回答
32

上面的解决方案确实有效,但我发现它非常冗长......您可以使用自定义标记扩展,可以像这样使用:

<ListBox x:Name="lb" ItemsSource="{my:SettingBinding Names}" />

这是此扩展的代码:

public class SettingBindingExtension : Binding
{
    public SettingBindingExtension()
    {
        Initialize();
    }

    public SettingBindingExtension(string path)
        :base(path)
    {
        Initialize();
    }

    private void Initialize()
    {
        this.Source = WpfApplication1.Properties.Settings.Default;
        this.Mode = BindingMode.TwoWay;
    }
}

更多细节在这里:http ://www.thomaslevesque.com/2008/11/18/wpf-binding-to-application-settings-using-a-markup-extension/

于 2009-05-10T23:19:01.250 回答
9

@CSharper 的答案不适用于我用 VB.NET 编码的 WPF 应用程序(不是 C#,显然不像 99.999% 的其他 WPF 应用程序),因为我得到一个持续的编译器错误,抱怨Settings在命名空间中找不到MyApp.Properties,这不会去即使在重建之后也消失了。

经过大量在线搜索后,对我有用的是使用local我的应用程序主窗口 XAML 文件中默认创建的 XAML 命名空间:

<Window
    <!-- Snip -->
    xmlns:local="clr-namespace:MyApp"
    <!-- Snip -->
><!-- Snip --></Window>

...并使用以下内容通过它绑定到我的设置(MyBooleanSetting我在类型和范围 User 的项目属性中定义的设置在哪里Boolean,使用默认的 Friend 访问修饰符):

<CheckBox IsChecked="{Binding Source={x:Static local:MySettings.Default}, Path=MyBooleanSetting, Mode=TwoWay}"
          Content="This is a bound CheckBox."/>

为确保实际保存设置,请务必调用

MySettings.Default.Save()

...在您的代码隐藏中的某个地方(例如在Me.Closing您的文件的事件中MainWindow.xaml.vb)。

(归功于此Visual Studio 论坛帖子的灵感;请参阅 Muhammad Siddiqi 的回复。)

于 2016-02-24T15:51:57.467 回答
0

这是我绑定用户设置的方式:

propdp通过键入然后 tab 两次来生成依赖变量。

    public UserSettings userSettings
    {
        get { return (UserSettings)GetValue(userSettingsProperty); }
        set { SetValue(userSettingsProperty, value); }
    }
    public static readonly DependencyProperty userSettingsProperty =
        DependencyProperty.Register("userSettings", typeof(UserSettings), typeof(MainWindow), new PropertyMetadata(UserSettings.Default));

现在,您可以通过以下方式绑定userSettings

Value="{Binding userSettings.SomeUserSettingHere, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"

并确保在更改用户设置或退出时保存用户设置:

UserSettings.Default.Save();
于 2020-01-13T19:26:32.043 回答