/ / WPF - ValidationRule не се нарича - c #, wpf, xaml, validationrules, validationrule

WPF - ValidationRule не се нарича - c #, wpf, xaml, validationrules, 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, когато избирам файл по диалоговия прозорец на файла?

Отговори:

4 за отговор № 1

Според тази статия в библиотеката на MSDN правилата за валидиране се проверяват само при прехвърляне на данни от целевата собственост на обвързването (TextBlock.Text в твоя случай) да се източник на собственост (вашият vm.FilesPath собственост) - целта тук е да се валидира приноса на потребителя от, например, a TextBox, За да даде обратна връзка за валидация от собствеността на източника до контрола, притежаващ целевата собственост ( TextBlock контрол), който моделът ви за наблюдение трябва да изпълни IDataErrorInfo или INotifyDataErrorInfo.