【问题标题】:Binding XAML controls to complex data type (PasswordCredential)将 XAML 控件绑定到复杂数据类型 (PasswordCredential)
【发布时间】:2026-02-02 21:05:02
【问题描述】:

我正在尝试创建一个带有设置页面的 Windows 10 应用程序,该页面允许用户输入应用程序将用于连接到外部服务的凭据。我想将这些凭据存储在 PasswordVault 中。

我以Template10 Template10 作为起点。我已将 TextBox 和 PasswordBox 添加到 Settings PivotItem。我已将 PasswordCredential 成员添加到 ISettingsService。而且,我在 SettingsService 类中添加了一个实现,用于从保管库中存储和检索 PasswordCredential 对象。

现在,我需要将 TextBox 和 PasswordBox 连接到 PasswordCredental 对象的 UserName 和 Password 属性。更新用户名/密码对时还需要执行一些逻辑。我是 XAML 的新手,我完全不知道如何让它工作。有什么建议吗?

【问题讨论】:

  • 如果您已经知道如何在 XAML 中绑定,请查看IValueConverter interface
  • @FilippoB 这对我来说是新的,但我正在尝试使用 IValueConverter 实现。但是,我似乎无法在 XAML 中解析对该类的引用。我正在尝试将 Text 值设置为“{Binding Path=PasswordCredentialObject, Converter={StaticResource Helpers:PasswordCredentialConverter}, ConverterParameter=UserName}”并且我添加了 xmlns:Helpers="using:WindowsApp1.Helpers 的命名空间引用",但它无法解析引用。
  • 解决了参考问题。我忽略了在我页面的 XAML 中声明转换器的静态资源。
  • 如果仍有问题,请告诉我,我会尽力详细解答

标签: winrt-xaml uwp template10


【解决方案1】:

这比你想象的要容易。假设这个模型:

public class UserCredentials : BindableBase
{
    string _userName = default(string);
    public string UserName { get { return _userName; } set { Set(ref _userName, value); } }

    string _password = default(string);
    public string Password { get { return _password; } set { Set(ref _password, value); } }
}

您可以在 XAML 中执行此操作:

<!-- login form -->
<StackPanel Grid.Row="1" Margin="20, 16" DataContext="{Binding ElementName=ThisPage}">
    <TextBox Header="Username" Text="{Binding UserCredentials.UserName, Mode=TwoWay}" />
    <TextBox Header="Password" Text="{Binding UserCredentials.Password, Mode=TwoWay}" />
    <Button Click="LoginClicked" Margin="0,12,0,0" HorizontalAlignment="Right">Login</Button>
</StackPanel>

有意义吗?为了提供帮助,我将它添加到了模板 10 的 GitHub 存储库中的示例项目中,如果你想看到它工作的话。

祝你好运。

【讨论】: