我得到了一个TextBlock的Xaml:
<TextBlock VerticalAlignment="Center">
<TextBlock.Text>
<Binding Path="FilesPath" Mode="TwoWay" UpdateSourceTrigger="PropertyChanged">
<Binding.ValidationRules>
<viewModel:ExtensionRule></viewModel:ExtensionRule>
</Binding.ValidationRules>
</Binding>
</TextBlock.Text>
</TextBlock>
在ViewModel中:
private string _filesPath;
public string FilesPath
{
set
{
_filesPath = value;
OnPropertyChange("FilesPath");
}
get { return _filesPath; }
}
private void OnPropertyChange(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
,验证规则如下:
public class ExtensionRule : 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");
}
string ext = Path.GetExtension(filePath);
if (!ext.ToLower().Contains("txt"))
{
return new ValidationResult(false, "given file does not end with the \".txt\" file extenstion");
}
return new ValidationResult(true, null);
}
}
并且FilesPath属性正在被另一个事件更新:(vm是viewModel var)
private void BrowseButton_Click(object sender, RoutedEventArgs e)
{
// Create OpenFileDialog
OpenFileDialog dlg = new OpenFileDialog();
// Set filter for file extension and default file extension
dlg.DefaultExt = ".txt";
dlg.Filter = "txt Files (*.txt)|*.txt";
// Display OpenFileDialog by calling ShowDialog method
bool? result = dlg.ShowDialog();
// Get the selected file name and display in a TextBox
if (result == true)
{
// Open document
string filename = dlg.FileName;
vm.FilesPath = filename;
}
}
为什么在我通过文件对话框选择文件时不会调用ValidationRule?
答案 0 :(得分:4)
根据this MSDN Library article验证规则仅在将数据从绑定的目标属性(在您的情况下为TextBlock.Text
)传输到源属性(您的vm.FilesPath
属性)时进行检查 - 此处的目的是验证用户输入,例如,TextBox
。为了从源属性向拥有目标属性(TextBlock
控件)的控件提供验证反馈,您的视图模型应实现IDataErrorInfo
或INotifyDataErrorInfo
。