将TextBox绑定到设置是';t工作

本文关键字:工作 TextBox 绑定 设置 | 更新日期: 2023-09-27 18:27:46

我最近正在处理一些WPF代码,遇到了一个大问题。我添加了visual studio生成的Setting,我想在窗口中使用它作为绑定。所以我创建了这样的东西:

<TextBox VerticalAlignment="Center" Grid.Row="0" Grid.Column="1" Name="username_textbox"   Text="{Binding Source={StaticResource Settings}, Mode=TwoWay, Path=Default.Password}" />

这是可以的,当我在App.xaml:上声明时

<Application x:Class="BlinkLinkClient.App"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            xmlns:properties="clr-namespace:BlinkLinkClient.Properties"
            ShutdownMode="OnExplicitShutdown">
   <Application.Resources>
       <ResourceDictionary>
           <ResourceDictionary.MergedDictionaries>
              <ResourceDictionary Source="GeneralResourceDictionary.xaml" />
           </ResourceDictionary.MergedDictionaries>
           <properties:Settings x:Key="Settings" />
       </ResourceDictionary>
   </Application.Resources>
</Application>

但我在网上发现这种方法有时会崩溃,所以我使用了另一种方法:

 <TextBox VerticalAlignment="Center" Grid.Row="1" Name="password_textbox" Text="{Binding Source={x:Static properties:Settings.Default}, Path=password}" Grid.Column="1" />

我的财产名称空间在哪里:

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

绑定时输出错误

System.Windows.Data错误:40:BindingExpression路径错误:在"对象"设置"(HashCode=32985660)上找不到"用户名"属性。BindingExpression:Path=用户名;DataItem="设置"(HashCode=32985660);目标元素是"TextBox"(名称=");目标属性是"文本"(类型为"字符串")

设置类(只有一个道具,每个道具都相似):

namespace BlinkLinkClient {

    [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
    [global::System.CodeDom.Compiler.GeneratedCodeAttribute
    ("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "12.0.0.0")]
    public partial class Settings : global::System.Configuration.ApplicationSettingsBase {
    private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
    public static Settings Default {
        get {
            return defaultInstance;
        }
    }
    [global::System.Configuration.UserScopedSettingAttribute()]
    [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
    [global::System.Configuration.DefaultSettingValueAttribute("user@gmail.com")]
    public string Username {
        get {
            return ((string)(this["Username"]));
        }
        set {
            this["Username"] = value;
        }
    }
}

什么都没有发生,数据没有存储,甚至没有显示(我提供默认值,并在其他代码中设置,我可以完全访问它)。我做错了什么?感谢

将TextBox绑定到设置是';t工作

第二种方法(StaticExtension获取Settings实例+Binding,设置名称为Path)是正确的。第一个方法不起作用,因为它创建了一个单独的设置实例,并且路径不正确(不能绑定到静态属性)。

请检查信箱。在第一个示例中,属性名为Password,但在第二个示例中为password。在"输出"窗口中查找绑定错误。您也可以尝试使用附加的PresentationTraceSources.TraceLevel属性进行调试。

此外,为了保存属性,您需要在某个地方调用Save()方法。绑定只会更改属性值,不会存储它们。