我得到了一个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?
发布于 2014-03-29 21:39:40
根据这篇MSDN库文章,只有当数据从绑定的目标属性(在您的情况下是TextBlock.Text)传输到源属性(您的vm.FilesPath属性)时,才会检查验证规则--这里的目的是验证来自例如TextBox的用户输入。为了从源属性向拥有目标属性( TextBlock控件)的控件提供验证反馈,视图模型应该实现IDataErrorInfo或INotifyDataErrorInfo。
https://stackoverflow.com/questions/22736668
复制相似问题