C# 使用 MVVM 时,如何使 TextBox 成为“密码框”并显示星星?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1119605/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I make a TextBox be a "password box" and display stars when using MVVM?
提问by Edward Tanguay
How can I do this in XAML:
如何在 XAML 中执行此操作:
PSEUDO-CODE:
伪代码:
<TextBox Text="{Binding Password}" Type="Password"/>
so that the user sees stars or dots when he is typing in the password.
以便用户在输入密码时看到星星或圆点。
I've tried various exampleswhich suggest PasswordCharand PasswordBoxbut can't get these to work.
我尝试了各种建议PasswordChar和PasswordBox 的示例,但无法使它们工作。
e.g. I can do this as shown here:
<PasswordBox Grid.Column="1" Grid.Row="1"
PasswordChar="*"/>
but I of course want to bind the Text property to my ViewModel so I can send the value the bound TextBox when the button is clicked (not working with code behind), I want to do this:
但我当然想将 Text 属性绑定到我的 ViewModel 以便我可以在单击按钮时将值发送到绑定的 TextBox(不使用后面的代码),我想这样做:
<TextBox Grid.Column="1" Grid.Row="0"
Text="{Binding Login}"
Style="{StaticResource FormTextBox}"/>
<PasswordBox Grid.Column="1" Grid.Row="1"
Text="{Binding Password}"
PasswordChar="*"
Style="{StaticResource FormTextBox}"/>
But PasswordBox doesn't have a Text property.
但是 PasswordBox 没有 Text 属性。
采纳答案by Brandon
To get or set the Password in a PasswordBox, use the Password property. Such as
要在 PasswordBox 中获取或设置密码,请使用 Password 属性。如
string password = PasswordBox.Password;
This doesn't support Databinding as far as I know, so you'd have to set the value in the codebehind, and update it accordingly.
据我所知,这不支持数据绑定,因此您必须在代码隐藏中设置值,并相应地更新它。
回答by gimpy
There's a way to bind on a PasswordBox here: PasswordBox Databinding
有一种方法可以在此处绑定PasswordBox:PasswordBox Databinding
回答by Cody C
Send the passwordbox control as a parameter to your login command.
将密码框控件作为参数发送到您的登录命令。
<Button Command="{Binding LoginCommand}" CommandParameter="{Binding ElementName=PasswordBox}"...>
Then you can call CType(parameter, PasswordBox).Password
in your viewmodel.
然后你可以调用CType(parameter, PasswordBox).Password
你的视图模型。
回答by Kwex
Thanks Cody, that was very helpful. I've just added an example for guys using the Delegate Command in C#
谢谢科迪,这很有帮助。我刚刚为在 C# 中使用委托命令的人添加了一个示例
<PasswordBox x:Name="PasswordBox"
Grid.Row="1" Grid.Column="1"
HorizontalAlignment="Left"
Width="300" Height="25"
Margin="6,7,0,7" />
<Button Content="Login"
Grid.Row="4" Grid.Column="1"
Style="{StaticResource StandardButton}"
Command="{Binding LoginCommand}"
CommandParameter="{Binding ElementName=PasswordBox}"
Height="31" Width="92"
Margin="5,9,0,0" />
public ICommand LoginCommand
{
get
{
return new DelegateCommand<object>((args) =>
{
// Get Password as Binding not supported for control-type PasswordBox
LoginPassword = ((PasswordBox) args).Password;
// Rest of code here
});
}
}
回答by Daniel_Uns
I did the below from the Views codebehind to set my property within the view model. Not sure if it really " breaks" the MVVM pattern but its the best and least complexe solution found.
我从视图代码隐藏中执行以下操作以在视图模型中设置我的属性。不确定它是否真的“打破”了 MVVM 模式,但它是找到的最好和最不复杂的解决方案。
var data = this.DataContext as DBSelectionViewModel;
data.PassKey = txtPassKey.Password;
回答by Tasnim Fabiha
You can make your TextBox
as customed PasswordBox
by simply adding the following value to FontFamily
property of your TextBox
control.
您可以通过简单地将以下值添加到您的控件属性来TextBox
定制您的自定义。PasswordBox
FontFamily
TextBox
<TextBox
Text="{Binding Password}"
FontFamily="ms-appx:///Assets/PassDot.ttf#PassDot"
FontSize="35"/>
In my case this works perfectly. This will show dot in place of the actual text (not star(*) though).
在我的情况下,这非常有效。这将显示点代替实际文本(虽然不是星号(*))。
回答by David
The problem with using the PasswordBox is that it is not very MVVM friendly due to the fact that it works with SecureString and therefore requires a shim to bind it to a String. You also cannot use the clipboard. While all these things are there for a reason, you may not require that level of security. Here is an alternative approach that works with the clipboard, nothing fancy. You make the TextBox text and background transparent and bind the text to a TextBlock underneath it. This textblock converts characters to * using the converter specified.
使用 PasswordBox 的问题在于它对 MVVM 不是很友好,因为它与 SecureString 一起工作,因此需要一个垫片将它绑定到一个字符串。您也不能使用剪贴板。虽然所有这些事情都是有原因的,但您可能不需要这种级别的安全性。这是一种适用于剪贴板的替代方法,没什么特别的。您使 TextBox 文本和背景透明,并将文本绑定到它下面的 TextBlock。此文本块使用指定的转换器将字符转换为 *。
<Window.Resources>
<local:TextToPasswordCharConverter x:Key="TextToPasswordCharConverter" />
</Window.Resources>
<Grid Width="200">
<TextBlock Margin="5,0,0,0" Text="{Binding Text, Converter={StaticResource TextToPasswordCharConverter}, UpdateSourceTrigger=PropertyChanged, Mode=OneWay}" FontFamily="Consolas" VerticalAlignment="Center" />
<TextBox Foreground="Transparent" Text="{Binding Text, UpdateSourceTrigger=PropertyChanged}" FontFamily="Consolas" Background="Transparent" />
</Grid>
And here is the Value Converter:
这是价值转换器:
class TextToPasswordCharConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return new String('*', value?.ToString().Length ?? 0);
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
Make sure your Text property on your viewmodel implements INotifyPropertyChanged
确保您的视图模型上的 Text 属性实现 INotifyPropertyChanged
回答by ssamko
As Tasnim Fabiha mentioned, it is possible to change font for TextBox in order to show only dots/asterisks. But I wasn't able to find his font...so I give you my working example:
正如 Tasnim Fabiha 提到的,可以更改 TextBox 的字体以仅显示点/星号。但是我找不到他的字体……所以我给你我的工作示例:
<TextBox Text="{Binding Password}"
FontFamily="pack://application:,,,/Resources/#password" />
Just copy-paste won't work. Firstly you have to download mentioned font "password.ttf" link: https://github.com/davidagraf/passwd/blob/master/public/ttf/password.ttfThen copy that to your project Resources folder (Project->Properties->Resources->Add resource->Add existing file). Then set it's Build Action to: Resource.
只是复制粘贴是行不通的。首先,您必须下载提到的字体“password.ttf”链接:https: //github.com/davidagraf/passwd/blob/master/public/ttf/password.ttf然后将其复制到您的项目资源文件夹(Project->Properties ->资源->添加资源->添加现有文件)。然后将它的 Build Action 设置为:Resource。
After this you will see just dots, but you can still copy text from that, so it is needed to disable CTRL+C shortcut like this:
在此之后,您将只看到点,但您仍然可以从中复制文本,因此需要像这样禁用 CTRL+C 快捷方式:
<TextBox Text="{Binding Password}"
FontFamily="pack://application:,,,/Resources/#password" >
<TextBox.InputBindings>
<!--Disable CTRL+C -->
<KeyBinding Command="ApplicationCommands.NotACommand"
Key="C"
Modifiers="Control" />
</TextBox.InputBindings>
</TextBox>
回答by Nitika Chopra
This code definite helps you
此代码肯定可以帮助您
<PasswordBox x:Name="Password" InputScope="Password" />
Thanks!!!
谢谢!!!