gpt4 book ai didi

c# - Caliburn.Micro 支持密码盒吗?

转载 作者:行者123 更新时间:2023-12-01 16:35:20 25 4
gpt4 key购买 nike

Caliburn.Micro 主页 http://caliburnmicro.com提出以下声明,但我无法使用该示例中我能想到的任何变体使 CM 与 PasswordBox 控件一起使用。无论如何,不​​明白这是如何工作的,因为名称的大小写不同。有谁有一个 CM 示例可以让我获取 PasswordBox 的值吗?是否需要特定版本的 CM?我正在运行 CM 1.5.2 版本。理想情况下不使用附加属性,但如果可以与 CM 一起使用,并且是唯一的方法,那么就可以了。请不要就安全问题进行讲座,因为这对我来说不是问题。

<小时/>

使用参数和保护方法自动在 View 和 View 模型之间应用方法

<StackPanel>
<TextBox x:Name="Username" />
<PasswordBox x:Name="Password" />
<Button x:Name="Login" Content="Log in" />
</StackPanel>

public bool CanLogin(string username, string password)
{
return !String.IsNullOrEmpty(username) && !String.IsNullOrEmpty(password);
}

public string Login(string username, string password)
{
...
}

最佳答案

这是一个更加简化的示例,包括绑定(bind)约定,以便 Caliburn.Micro Just Works™ 中的 PasswordBox 绑定(bind):

public static class PasswordBoxHelper
{
public static readonly DependencyProperty BoundPasswordProperty =
DependencyProperty.RegisterAttached("BoundPassword",
typeof(string),
typeof(PasswordBoxHelper),
new FrameworkPropertyMetadata(string.Empty, OnBoundPasswordChanged));

public static string GetBoundPassword(DependencyObject d)
{
var box = d as PasswordBox;
if (box != null)
{
// this funny little dance here ensures that we've hooked the
// PasswordChanged event once, and only once.
box.PasswordChanged -= PasswordChanged;
box.PasswordChanged += PasswordChanged;
}

return (string)d.GetValue(BoundPasswordProperty);
}

public static void SetBoundPassword(DependencyObject d, string value)
{
if (string.Equals(value, GetBoundPassword(d)))
return; // and this is how we prevent infinite recursion

d.SetValue(BoundPasswordProperty, value);
}

private static void OnBoundPasswordChanged(
DependencyObject d,
DependencyPropertyChangedEventArgs e)
{
var box = d as PasswordBox;

if (box == null)
return;

box.Password = GetBoundPassword(d);
}

private static void PasswordChanged(object sender, RoutedEventArgs e)
{
PasswordBox password = sender as PasswordBox;

SetBoundPassword(password, password.Password);

// set cursor past the last character in the password box
password.GetType().GetMethod("Select", BindingFlags.Instance | BindingFlags.NonPublic).Invoke(password, new object[] { password.Password.Length, 0 });
}

}

然后,在您的 Bootstrap 中:

public sealed class Bootstrapper : BootstrapperBase
{
public Bootstrapper()
{
Initialize();

ConventionManager.AddElementConvention<PasswordBox>(
PasswordBoxHelper.BoundPasswordProperty,
"Password",
"PasswordChanged");
}

// other bootstrapper stuff here
}

关于c# - Caliburn.Micro 支持密码盒吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30631522/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com