C# 两种不同模型上的共享验证逻辑
更新:我一直在摆弄一个解决方案,我不太确定我们是否可以这样做。一旦我对我想要的东西有了更好的了解,我会尽快更新问题:-)C# 两种不同模型上的共享验证逻辑,c#,wpf,validation,c#-4.0,mvvm,C#,Wpf,Validation,C# 4.0,Mvvm,更新:我一直在摆弄一个解决方案,我不太确定我们是否可以这样做。一旦我对我想要的东西有了更好的了解,我会尽快更新问题:-) 我们当前的项目使用WPF和MVVM方法。我们的应用程序将有几个编辑器,每个编辑器都有自己的模型 视图将如下所示: interface IValidateModel { string foo; } class Editor1Model : IValidateModel { string foo; int someOtherProperty; } class E
我们当前的项目使用WPF和MVVM方法。我们的应用程序将有几个编辑器,每个编辑器都有自己的模型 视图将如下所示:
interface IValidateModel
{
string foo;
}
class Editor1Model : IValidateModel
{
string foo;
int someOtherProperty;
}
class Editor2Model: IValidateModel
{
string foo;
byte fooBar;
}
class ParentModel
{
Sub subProp;
// some other parent model properties
}
<TextBox>
<TextBox.Text>
<Binding Path="MyPath">
<Binding.ValidationRules>
<vr:TestRule />
</Binding.ValidationRules>
</Binding>
</TextBox.Text>
</TextBox>
每个编辑器都有自己的模型/视图模型/模型。父视图的(包含所有子编辑器)模型包含所有子编辑器可以从中馈送的数据
由于用户应该能够随时保存其当前状态,因此我们还需要能够验证现有数据(因为用户可能输入了无效数据)。因此,我们需要在两个地方进行验证:
- 当用户输入数据时
- 启动应用程序后再次加载数据时
interface IValidateModel
{
string foo;
}
class Editor1Model : IValidateModel
{
string foo;
int someOtherProperty;
}
class Editor2Model: IValidateModel
{
string foo;
byte fooBar;
}
class ParentModel
{
Sub subProp;
// some other parent model properties
}
<TextBox>
<TextBox.Text>
<Binding Path="MyPath">
<Binding.ValidationRules>
<vr:TestRule />
</Binding.ValidationRules>
</Binding>
</TextBox.Text>
</TextBox>
曾经的缺点是,现在数据的结构是由接口定义的
是否有人对此问题有经验,或者有更好的解决方案?如果要验证用户的输入,则应在绑定上使用 您可以通过继承
ValidationRule
并覆盖Validate()
来定义它们:
在XAML中,指定验证规则的命名空间:
<Window xmlns:vr="clr-namespace:MyApp.ValidationRules"></Window>
然后您可以在如下绑定上使用它:
interface IValidateModel
{
string foo;
}
class Editor1Model : IValidateModel
{
string foo;
int someOtherProperty;
}
class Editor2Model: IValidateModel
{
string foo;
byte fooBar;
}
class ParentModel
{
Sub subProp;
// some other parent model properties
}
<TextBox>
<TextBox.Text>
<Binding Path="MyPath">
<Binding.ValidationRules>
<vr:TestRule />
</Binding.ValidationRules>
</Binding>
</TextBox.Text>
</TextBox>
我不是英语母语,所以这可能就是我不能完全理解你的问题的原因。请您发布一个更具体/实际的示例/代码,好吗?您是如何进行验证的?您调用的IValidateModel
接口已经存在于WPF中,它的名称为IDataErrorInfo
。通过使用它,您可以将验证委托给模型(无论有多少个ViewModels)。您可以阅读一篇关于IDataErrorInfo
validation的文章。也许它适合你的项目。