Можно ли пометить свойство, отображаемое в таблице свойств, в качестве поля пароля
-
22-07-2019 - |
Вопрос
Я использую C # и у меня есть форма Windows, содержащая элемент управления property grid.
Я назначил selectedObject из propertygrid файлу настроек, который отображает и позволяет мне редактировать настройки.Однако одним из параметров является пароль, и я бы хотел, чтобы в поле отображались звездочки, а не обычное текстовое значение параметра пароля.
Поле будет зашифровано при сохранении, но я хочу, чтобы оно вело себя как обычное поле для ввода пароля со звездочками, отображаемыми, когда пользователь вводит пароль.
Мне интересно, есть ли атрибут, который можно применить к свойству setting, чтобы пометить его как пароль?
Спасибо.
Решение
Начиная с .Net 2, вы можете использовать Атрибут PasswordPropertyTextAttribute прикрепленный к вашему свойству password.
Надеюсь, это поможет.
Другие советы
Вот что я делал в прошлом.Он отображает "********" пароль в таблице с кнопкой "...", позволяющей пользователю установить пароль (используя предоставленное вами диалоговое окно).
public class User
{
[TypeConverter(typeof(PasswordConverter))]
[Editor(typeof(PasswordEditor), typeof(UITypeEditor))]
public string Password { get; set; }
}
public class PasswordConverter : TypeConverter
{
public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
{
if (destinationType == typeof(string)) return true;
return base.CanConvertTo(context, destinationType);
}
public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType)
{
if (destinationType == typeof(string))
{
string password = (string)value;
if (password != null && password.Length > 0)
{
return "********";
}
}
return base.ConvertTo(context, culture, value, destinationType);
}
}
public class PasswordEditor : UITypeEditor
{
public override object EditValue(ITypeDescriptorContext context, IServiceProvider provider, object value)
{
string password = (string)value;
// Show a dialog allowing the user to enter a password
return password;
}
public override UITypeEditorEditStyle GetEditStyle(ITypeDescriptorContext context)
{
return UITypeEditorEditStyle.Modal;
}
}
Я не думаю, что вы можете заставить PropertyGrid поменять местами звездочки, но, возможно, вы могли бы использовать односторонний преобразователь типов и модальный редактор...вот так:
using System;
using System.ComponentModel;
using System.Drawing.Design;
using System.Windows.Forms;
using System.Windows.Forms.Design;
class Foo
{
[TypeConverter(typeof(PasswordConverter))]
[Editor(typeof(PasswordEditor), typeof(UITypeEditor))]
public string Password { get; set; }
// just to show for debugging...
public string PasswordActual { get { return Password; } }
}
class PasswordConverter : TypeConverter
{
public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, System.Type destinationType)
{
return destinationType == typeof(string) ? "********" :
base.ConvertTo(context, culture, value, destinationType);
}
}
class PasswordEditor : UITypeEditor
{
public override UITypeEditorEditStyle GetEditStyle(ITypeDescriptorContext context)
{
return UITypeEditorEditStyle.Modal;
}
public override object EditValue(ITypeDescriptorContext context, IServiceProvider provider, object value)
{
IWindowsFormsEditorService svc = (IWindowsFormsEditorService)
provider.GetService(typeof(IWindowsFormsEditorService));
if (svc != null) {
TextBox tb;
Button btn;
Form frm = new Form { Controls = {
(tb = new TextBox { PasswordChar = '*', Dock = DockStyle.Top,
Text = (string)value}),
(btn = new Button { Text = "OK", Dock = DockStyle.Bottom, DialogResult = DialogResult.OK})
}, AcceptButton = btn};
if (frm.ShowDialog() == DialogResult.OK)
{
value = tb.Text;
}
}
return value;
}
}
static class Program {
[STAThread]
static void Main() {
Application.EnableVisualStyles();
Application.Run(new Form {
Controls = {
new PropertyGrid {
Dock = DockStyle.Fill,
SelectedObject = new Foo { Password = "Bar"}
}
}
});
}
}