WPF - ValidationRule没有被调用
本文关键字:调用 ValidationRule WPF | 更新日期: 2023-09-27 18:09:46
这是我之前问过的一个问题的后续问题:
WPF - ValidationRule未被调用
我被告知我应该实现INotifyDataErrorInfo
,所以我做了,但它仍然不起作用。
<TextBlock VerticalAlignment="Center">
<TextBlock.Text>
<Binding Path="Path" Mode="TwoWay" UpdateSourceTrigger="PropertyChanged">
<Binding.ValidationRules>
<viewModel:StrRule/>
</Binding.ValidationRules>
</Binding>
</TextBlock.Text>
</TextBlock>
在ViewModel中:
private string _path;
public string Path
{
set
{
_path = value;
OnPropertyChange("Path");
}
get { return _path; }
}
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChange(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
private Dictionary<String, List<String>> errors = new Dictionary<string, List<string>>();
public event EventHandler<DataErrorsChangedEventArgs> ErrorsChanged;
private void SetErrors(string propertyName, List<string> propertyErrors)
{
// Clear any errors that already exist for this property.
errors.Remove(propertyName);
// Add the list collection for the specified property.
errors.Add(propertyName, propertyErrors);
// Raise the error-notification event.
if (ErrorsChanged != null)
ErrorsChanged(this, new DataErrorsChangedEventArgs(propertyName));
}
private void ClearErrors(string propertyName)
{
// Remove the error list for this property.
errors.Remove(propertyName);
// Raise the error-notification event.
if (ErrorsChanged != null)
ErrorsChanged(this, new DataErrorsChangedEventArgs(propertyName));
}
public System.Collections.IEnumerable GetErrors(string propertyName)
{
if (string.IsNullOrEmpty(propertyName))
{
// Provide all the error collections.
return (errors.Values);
}
else
{
// Provice the error collection for the requested property
// (if it has errors).
if (errors.ContainsKey(propertyName))
{
return (errors[propertyName]);
}
else
{
return null;
}
}
}
public bool HasErrors
{
get
{
return errors.Count > 0;
}
}
和验证规则:
public class StrRule : ValidationRule
{
public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo)
{
string filePath = String.Empty;
filePath = (string)value;
if (String.IsNullOrEmpty(filePath))
{
return new ValidationResult(false, "Must give a path");
}
if (!File.Exists(filePath))
{
return new ValidationResult(false, "File not found");
}
return new ValidationResult(true, null);
}
}
我也得到了一个按钮,打开一个FileDialog,然后更新ViewModels的路径属性。
当TextBlock被更新时,绑定本身工作并且set属性被调用,但不是验证规则本身。这里缺少/错了什么?
如评论 ValidationRule
仅在绑定从 Target
(TextBlock Text)更新到 Source
(ViewModel属性)时调用。
因此,不是直接设置源值vm.FilesPath = filename;
,而是设置TextBlock文本值和验证规则 Validate
方法将被调用。