首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >没有调用WPF - ValidationRule。

没有调用WPF - ValidationRule。
EN

Stack Overflow用户
提问于 2014-03-29 20:44:11
回答 1查看 1.8K关注 0票数 0

我得到了一个TextBlock的Xaml:

代码语言:javascript
复制
<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中:

代码语言:javascript
复制
    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));
        }
    }

验证规则是:

代码语言:javascript
复制
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)

代码语言:javascript
复制
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?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-03-29 21:39:40

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

票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/22736668

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档