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但暴露封裝的對象。
謝謝。這是工作。 – 2012-07-10 02:38:55