2

In a wpf view, i have 3 textboxes which implement a custom validation rules like this :

<TextBox HorizontalAlignment="Left"
         Height="30"
         Grid.Row="2"
         Grid.Column="1"
         TextWrapping="Wrap"
         VerticalAlignment="Top"
         Width="150"
         Validation.ErrorTemplate="{StaticResource ValidationTemplate}">
  <TextBox.Text>
    <Binding Path="Model.Age"
             Mode="TwoWay"
             UpdateSourceTrigger="PropertyChanged"
             ValidatesOnExceptions="True"
             ValidatesOnDataErrors="True">
      <Binding.ValidationRules>
        <validation:DataTypeValidationRules DataTypeRule="Required"
                                            ErrorMessage="Required field" />
      </Binding.ValidationRules>
    </Binding>
  </TextBox.Text>
</TextBox>

My problem is : If i change the text directly in textbox, the validation work and i can see my template if the textbox has no value, but if i do nothing in the view and click on my save button, which has a command binding to my ViewModel, the validation is not working, because i think there is no OnPropertyChange event who was raised, so i need to check again if the value is not empty in my viewmodel, and i don't want to do this like that.

Note : I'm using the MVVM pattern

Sorry for my English and many thanks for your responses.

4

1 回答 1

2

我能想到这个问题可能发生的唯一方法是当文本是从视图模型而不是从 UI 设置时,在这种情况下这确实是一个问题,因为验证规则不会被重新评估。

为了解决这个问题,您可以实现IDataErrorInfointerface,或者更好的是实现INotifyDataErrorInfointerface(如果您的目标是 .NET 4.5)。这不仅可以解决您的问题,而且还是 MVVM 执行验证的方式(您当前正在 XAML 中定义验证逻辑,这并不好)。执行此操作后,您也可以从 XAML 中删除绑定规则。

实现示例:

public class ViewModel : IDataErrorInfo
{
    public string Error
    {
        get { return null; }
    }

    public string this[string propertyName]
    {
        get
        {
            if (propertyName == "Age")
            {
                if (Age < 18)
                {
                    return "Age must be at least 18.";
                }
            }

            return null;
        }
    }
}
于 2013-07-02T20:05:43.533 回答