0
我TextBlock的此XAML:WPF - 有效性規則不被稱爲
<TextBlock VerticalAlignment="Center">
<TextBlock.Text>
<Binding Path="FilesPath" Mode="TwoWay" UpdateSourceTrigger="PropertyChanged">
<Binding.ValidationRules>
<viewModel:ExtensionRule></viewModel:ExtensionRule>
</Binding.ValidationRules>
</Binding>
</TextBlock.Text>
</TextBlock>
在視圖模型:
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?
是否有可能VS2010不支持INotifyDataErrorInfo,但只支持IDataErrorInfo? –
@YonatanNir - 「INotifyDataErrorInfo」僅在.NET 4.5中引入,VS2010僅支持.NET 4.0以上的目標框架版本,因此它將不可用。 – Grx70
但我不明白的是爲什麼它無法正常工作。我知道INotifyDataErrorInfo應該在直接更改屬性時使用,而不是通過綁定,但該屬性仍然實現INotifyPropertyChanged ..這是否意味着它應該使用validationRule?由於使用INotifyDataErrorInfo,該規則根本不會被使用 –