我正在尝试根据ViewModel公开的属性构建我的应用程序设置页面。我正在使用.Net 4.0和MVVM。 ViewModel公开单个Collection“设置值组”。组表示彼此依赖且属于域的逻辑组的属性。视图中的设置页面使用DataTemplate创建,如下所示: -
<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>
然后我在ViewModel模块中有一个类来表示“设置组”,如下所示:
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;
}
}
}
最后,viewModel公开了这样一组设置的集合:
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;
}
}
问题:调用属性设置器,但只要更改了UI值,就不会调用数据验证 。我已经尝试过将IDataErrorInfo实现放在ViewModel类中但是没有效果。我将使用一组设置,因为这些应用程序设置在许多项目中使用,我们不希望每个应用程序都有重复的XAML。 注意: viewmodel未公开UI绑定到的属性,例如Field1Value但暴露了封装对象。
答案 0 :(得分:2)
您没有告诉您的观点,您要绑定的属性需要进行验证。使用&#34; ValidatesOnDataErrors = true&#34;在你的绑定。
<TextBox Text="{Binding Field1Value, Mode=TwoWay, ValidatesOnDataErrors=True}" Grid.Column="2" />