![](/img/trans.png)
[英]Adding custom icons from the Bootstrap causes “stack overflow state” error
[英]Stack OverFlow with Custom validator
我已經實現了以下自定義驗證器...
public class RquiredFiledValidation:ValidationRule
{
public string ErrorMessage { get; set; }
public override ValidationResult Validate(object value, CultureInfo cultureInfo)
{
if (string.IsNullOrWhiteSpace(value.ToString()))
return new ValidationResult(false, ErrorMessage);
else
return new ValidationResult(true, null);
}
}
並附上以下文本框...
<TextBox x:Name="txtLoging" Grid.Column="1" HorizontalAlignment="Stretch" Validation.ErrorTemplate="{x:Null}" VerticalAlignment="Center" Margin="0,40,30,0">
<Binding Path="Text" ElementName="txtLoging" UpdateSourceTrigger="PropertyChanged" ValidatesOnDataErrors="True">
<Binding.ValidationRules>
<Validate:RquiredFiledValidation ErrorMessage="Please Provide Login Name"></Validate:RquiredFiledValidation>
</Binding.ValidationRules>
</Binding>
</TextBox>
我的問題是
1)當我直接單擊登錄按鈕時,驗證不會被觸發
2)當我在文本框中輸入字符時,會被觸發,但會產生堆棧溢出錯誤。
我已經從下面的代碼中解決了第一個問題,如下txtLoging.GetBindingExpression(TextBox.TextProperty).UpdateSource(); txtPassword.GetBindingExpression(Infrastructure.AttachedProperty.PasswordAssistent.PasswordValue).UpdateSource(); 但是如何在MVVM中解決相同問題
如果您關心MVVM模式,則不應使用驗證規則來驗證數據。 驗證規則屬於視圖,並且在MVVM應用程序中,驗證邏輯應在視圖模型或模型類中實現。
您應該做的是實現INotifyDataErrorInfo接口: https ://msdn.microsoft.com/zh-cn/library/system.componentmodel.inotifydataerrorinfo%28v=vs.110%29.aspx
這是給你的一個例子:
public class ViewModel : INotifyDataErrorInfo
{
private string _username;
public string Username
{
get { return _username; }
set
{
_username = value;
ValidateUsername();
}
}
private void ValidateUsername()
{
if (_username == "valid")
{
if (_validationErrors.ContainsKey("Username"))
_validationErrors.Remove(nameof(Username));
}
else if (!_validationErrors.ContainsKey("Username"))
{
_validationErrors.Add("Username", new List<string> { "Invalid username" });
}
RaiseErrorsChanged("Username");
}
private readonly Dictionary<string, ICollection<string>>
_validationErrors = new Dictionary<string, ICollection<string>>();
public event EventHandler<DataErrorsChangedEventArgs> ErrorsChanged;
private void RaiseErrorsChanged(string propertyName)
{
if (ErrorsChanged != null)
ErrorsChanged(this, new DataErrorsChangedEventArgs(propertyName));
}
public System.Collections.IEnumerable GetErrors(string propertyName)
{
if (string.IsNullOrEmpty(propertyName)
|| !_validationErrors.ContainsKey(propertyName))
return null;
return _validationErrors[propertyName];
}
public bool HasErrors
{
get { return _validationErrors.Count > 0; }
}
}
<TextBox Text="{Binding Username, UpdateSourceTrigger=PropertyChanged, ValidatesOnNotifyDataErrors=True}" />
請參考以下博客文章,以獲取有關WPF中數據驗證的工作原理的廣泛信息以及有關如何實現它的一些綜合示例的更多信息。
WPF中的數據驗證: https : //blog.magnusmontin.net/2013/08/26/data-validation-in-wpf/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.