gpt4 book ai didi

mvvm - 如何在 ViewModel 中获取实际值并验证 CustomTextbox 文本

转载 作者:行者123 更新时间:2023-12-02 05:07:34 26 4
gpt4 key购买 nike

我已经创建了自定义组件以使用简单或密码模式显示文本,开发此控件的目的是Silverlight 不支持自定义 TextMode(如密码或文本)。

这是我的要求除了访问权限之外,组织还可以指定对数据库中某些字段的限制访问。对这些字段的访问限制将是 Update 和 Redacted,因此意味着如果特定字段针对 Update 为真,则用户将能够更新该字段以及查看它,如果该字段针对 Redacted 为真,则用户将只能在归档中看到经过编辑的值(可能是星号 - * * * * *)。可以将字段设置为可更新和已编辑,这意味着用户将看到已编辑的 View ,但仍然能够使用新值更新该字段。这种要求主要用于持有针对联系人的敏感信息或可用于歧视联系人的信息。

我已经为此要求创建了自定义控件,并且它运行良好。我可以动态设置 TextMode,但无法在我的 ViewModel 中获取原始值。 (我可以在 View 中获取原始值,但不能在 ViewModel 中获取)

如果我使用以下方法访问 View 中的原始值,那么它就可以工作。

string s = UserName.Text;

但在 ViewModel 中没有得到这个值,它给了我**

以下是PasswordTextBox控件的完整代码。

namespace QSys.Library.Controls
{
public partial class PasswordTextBox : TextBox
{
#region Variables
private string text = string.Empty;
private string passwordChar = "*";
private int selectionLength = 0;
#endregion

#region Properties
/// <summary>
/// The text associated with the control.
/// </summary>
public new string Text
{
get { return text; }
set
{
text = value;
DisplayMaskedCharacters();
}
}
/// <summary>
/// Indicates the character to display for password input.
/// </summary>
public string PasswordChar
{
get { return passwordChar; }
set { passwordChar = value; }
}
/// <summary>
/// Indicates the input text mode to display for either text or password.
/// </summary>
public Mode TextMode
{
get { return (Mode)GetValue(TextModeProperty); }
set { SetValue(TextModeProperty, value); }
}
public static readonly DependencyProperty TextModeProperty = DependencyProperty.Register("TextMode", typeof(Mode), typeof(PasswordTextBox), new PropertyMetadata(default(Mode)));
#endregion

#region Constructors
public PasswordTextBox()
{
this.Loaded += new RoutedEventHandler(PasswordTextBox_Loaded);
}
#endregion

#region Event Handlers
void PasswordTextBox_Loaded(object sender, System.Windows.RoutedEventArgs e)
{
if (this.TextMode == Mode.Password)
{
text = base.Text;
this.TextChanged += new TextChangedEventHandler(PasswordTextBox_TextChanged);
this.KeyDown += new KeyEventHandler(PasswordTextBox_KeyDown);
this.SelectionChanged += new RoutedEventHandler(PasswordTextBox_SelectionChanged);
DisplayMaskedCharacters();
}
this.Loaded -= PasswordTextBox_Loaded;
}
void PasswordTextBox_SelectionChanged(object sender, RoutedEventArgs e)
{
selectionLength = this.SelectionLength;
}
public void PasswordTextBox_TextChanged(object sender, TextChangedEventArgs e)
{
if (base.Text.Length >= text.Length)
text += base.Text.Substring(text.Length);
else
{
int cursorPosition = this.SelectionStart;
selectionLength = (selectionLength > 1) ? selectionLength : 1;
text = text.Remove(cursorPosition, selectionLength);
}
DisplayMaskedCharacters();
selectionLength = 0;
}
public void PasswordTextBox_KeyDown(object sender, System.Windows.Input.KeyEventArgs e)
{
int cursorPosition = this.SelectionStart;
// Handle Delete and Backspace Keys Appropriately
if (e.Key == System.Windows.Input.Key.Back && cursorPosition > 0)
{
DeleteAt(cursorPosition);
}
else if (e.Key == System.Windows.Input.Key.Delete)
{
DeleteAt(cursorPosition);
}
else
{
if (selectionLength > 0) text = text.Remove(cursorPosition, selectionLength);
base.Text = text;
this.Select((cursorPosition > text.Length ? text.Length : cursorPosition), 0);
DisplayMaskedCharacters();
}
selectionLength = 0;
}
#endregion

#region Private Methods
private void DisplayMaskedCharacters()
{
int cursorPosition = this.SelectionStart;
// This changes the Text property of the base TextBox class to display all Asterisks in the control
base.Text = new string(passwordChar.ToCharArray()[0], text.Length);
this.Select((cursorPosition > text.Length ? text.Length : cursorPosition), 0);
}
private void DeleteAt(int position)
{
if (text.Length > position)
{
text = text.Remove(position, 1);
base.Text = base.Text.Remove(position, 1);
}
}
#endregion
}
}

LoginView.xaml

<control:PasswordTextBox  x:Name="UserName" TabIndex="1" Grid.Row="1" TextMode="Password" Text="{Binding Path=LoginModelValue.UserName, Mode=TwoWay,ValidatesOnNotifyDataErrors=True, ValidatesOnExceptions=True, ValidatesOnDataErrors=True, NotifyOnValidationError=True}" HorizontalAlignment="Left" VerticalAlignment="Top" Grid.Column="1" Width="200" Height="25" Validatevalue:UpdateSourceTriggerHelper.UpdateSourceTrigger="True"/>

LoginViewModel.cs

public class LoginViewModel : INotifyPropertyChanged, IRegionMemberLifetime
{
public LoginModel LoginModelValue
{
get { return _LoginModelValue; }
set
{
_LoginModelValue = value;
OnPropertyChanged("LoginModelValue");
}
}
}

LoginModel.cs

namespace QSys.Model
{
public class LoginModel : INotifyPropertyChanged
{
#region Variables
private string _userName;
private string _password;
#endregion

#region Constructor
public LoginModel()
{
}
#endregion

#region Properties
[CustomValidation(typeof(PasswordTextBox), "IsValidUserName")]
[Required(ErrorMessage = "User Name is required")]
[Display(Name = "UserName")]
[StringLength(50)]
//[RegularExpression(@"^[a-zA-Z\\0-9\\.\\,\\'\s]+$", ErrorMessage = "Please enter right format.")]
public string UserName
{
get { return _userName; }
set
{
_userName = value;
OnPropertyChanged("UserName");
ValidateProperty("UserName", value);
}
}
[Required(ErrorMessage = "Password is required")]
[Display(Name = "Password")]
[StringLength(10)]
public string Password
{
get { return _password; }
set
{
_password = value;
OnPropertyChanged("Password");
ValidateProperty("Password", value);
}
}
#endregion

#region INotifyPropertyChanged
public event PropertyChangedEventHandler PropertyChanged = delegate { };
private void OnPropertyChanged(string propertyName)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
#endregion

#region Private Methods
public bool IsValidObject()
{
ICollection<ValidationResult> results = new Collection<ValidationResult>();
return Validator.TryValidateObject(this, new ValidationContext(this, null, null), results, true) && results.Count == 0;
}
public void ValidateProperty(string propertyName, object value)
{
Validator.ValidateProperty(value, new ValidationContext(this, null, null) { MemberName = propertyName });
}
#endregion
}
}

**我已经两天没有运气了,一直在寻找解决方案。

如果您有任何解决方案,请帮助我,您的意见或建议将不胜感激。**

谢谢

伊达胡森

最佳答案

围绕常规 TextBoxPasswordBox 构建您自己的 UserControl 并在您的依赖属性时切换它们的可见性会不会更容易TextMode 改变了吗?然后,您可以为具有属性 ValueUserControl 设置一个 VM,并在 TwoWay 模式下绑定(bind) TextProperty TextBoxPasswordBoxPassword 属性。

关于mvvm - 如何在 ViewModel 中获取实际值并验证 CustomTextbox 文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9460808/

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