WPF - ValidationRule не вызывается
Я получил этот Xaml TextBlock:
<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 не вызывается, когда я выбираю файл в диалоговом окне?
1 ответ
В соответствии с этой статьей MSDN Library правила проверки проверяются только при передаче данных из целевого свойства привязки (TextBlock.Text
в вашем случае) к источнику собственности (ваш vm.FilesPath
свойство) - цель состоит в том, чтобы проверить вводимые пользователем данные, например, из TextBox
, Для того, чтобы предоставить обратную связь валидации из свойства источника в элемент управления, владеющий целевым свойством (TextBlock
контроль) ваша модель представления должна реализовывать либо IDataErrorInfo
или же INotifyDataErrorInfo
,