2012-07-09 50 views
0

我试图根据ViewModel公开的属性构建我的应用程序设置页面。我正在使用.NET 4.0和MVVM。 ViewModel公开单个“设置值组”集合。组表示相互依赖并且属于逻辑组wrt到域的属性。鉴于设置页面使用的DataTemplate像下面创建: -在UI中使用数据模板时未触发IDataErrorInfo验证

<DataTemplate x:Key="contentSettingGroup1"> 
    <TextBlock Text="{Binding Field1Description}" /> 
    <TextBox Text="{Binding Field1Value, Mode=TwoWay}" Grid.Column="2" /> 

    <TextBlock Text="{Binding Field2Description}" /> 
    <TextBox Text="{Binding Field2Value, Mode=TwoWay}" Grid.Column="6" /> 
</DataTemplate> 

<DataTemplate DataType="{x:Type vm:SettingGroup1}"> 
    <HeaderedContentControl Header="{Binding}" HeaderTemplate="{StaticResource titleArea}" Content="{Binding}" ContentTemplate="{StaticResource contentSettingGroup1}" /> 
</DataTemplate> 

然后我在视图模型模块类代表“的设置组”,如下:

public class SettingGroup1 : INotifyPropertyChanged, IDataErrorInfo 
{ 
    public double Field1value { get; private set; } 
    public double Field2value { get; private set; } 

    private double mField1; 
    public double Field1value 
    { 
     get { return mField1; } 
     set 
     { 
      if (mField1 != value) 
      { 
       mField1 = value; 
       RaisePropertyChanged(() => Field1value); 
      } 
     } 
    } 

    private double mField2; 
    public double Field2value 
    { 
     get { return mField2; } 
     set 
     { 
      if (mField2 != value) 
      { 
       mField2 = value; 
       RaisePropertyChanged(() => Field2value); 
      } 
     } 
    } 

    public string Error 
    { 
     get { return null; } 
    } 

    public string this[string property] 
    { 
     get 
     { 
      string errorMsg = null; 
      switch (property) 
      { 
       case "Field1value": 
        if (Field1value < 0.0) 
        { 
         errorMsg = "The entered value of Field1 is invalid !"; 
        } 
        if (Field1value < Field2value) 
        { 
         errorMsg = "The Field1 should be greater than Field2 !"; 
        } 
        break; 
      } 
      return errorMsg; 
     } 
    } 
} 

最后视图模型自曝这样的组设置的集合:

public ObservableCollection<object> Settings 
     { 
      get 
      { 
       var pageContents = new ObservableCollection<object>(); 
       var group1 = new SettingGroup1(); 
       group1.Field1.Description = "Description value 1"; 
       group1.Field1.Value = mValue1; 
       group1.Field2.Description = "Description value 2"; 
       group1.Field2.Value = mValue2; 
       pageContents.Add(group1); 

       // add other groups of controls 
       // ... 
       return pageContents; 
      } 
     } 

的问题:属性setter的调用,但数据验证是不CAL每当用户界面值发生变化时都会引发。我已经尝试在ViewModel类中放入IDataErrorInfo实现,但没有任何作用。我必须使用一组设置,因为这些应用程序设置在许多项目中使用,我们不希望每个应用程序都有重复的XAML。 注意: viewmodel并未公开UI绑定到的属性,例如, Field1Value但暴露封装的对象。

回答

2

您不会告诉您的看法,您绑定的属性需要验证。在绑定中使用“ValidatesOnDataErrors = true”。

<TextBox Text="{Binding Field1Value, Mode=TwoWay, ValidatesOnDataErrors=True}" Grid.Column="2" /> 
+0

谢谢。这是工作。 – 2012-07-10 02:38:55