0

我得到了这个 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>

在视图模型中:

    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 回答 1

4

根据此 MSDN 库文章验证规则仅在将数据从绑定的目标属性(TextBlock.Text在您的情况下)传输到源属性(您的vm.FilesPath属性)时检查 - 这里的目的是验证来自例如TextBox. 为了将来自源属性的验证反馈提供给拥有目标属性(TextBlock控件)的控件,您的视图模型应该实现IDataErrorInfoINotifyDataErrorInfo

于 2014-03-29T21:39:40.760 回答