问题是UI上没有显示红色矩形。
我使用Caliburn.Micro,这就是我在查看中的内容:
<StackPanel Grid.Row="0">
<Label>Customer name:</Label>
<TextBox x:Name="txtName" Text="{Binding Target.Model.Name, UpdateSourceTrigger=PropertyChanged, ValidatesOnDataErrors=True}" Width="136" HorizontalAlignment="Left"/>
</StackPanel>
以下是 ViewModel :
internal class ShellViewModel : Screen
{
private EditableCustomer _Target;
public EditableCustomer Target
{
get { return _Target; }
set { if (_Target != value) { _Target = value; NotifyOfPropertyChange(nameof(Target)); } }
}
}
这就是我在模型:
中的内容internal class EditableCustomer : PropertyChangedBase, IDataErrorInfo
{
private CustomerInfo _Model;
public CustomerInfo Model
{
get { return _Model; }
set { if (_Model != value) { _Model = value; NotifyOfPropertyChange(nameof(Model)); } }
}
}
这是另一个模型:
internal class CustomerInfo : PropertyChangedBase
{
private string _Name;
public string Name
{
get { return _Name; }
set { _Name = value; NotifyOfPropertyChange(nameof(Name)); }
}
}
我知道我可以将IDataErrorInfo接口从EditableCustomer转移到CustomerInfo模型,如果我这样做,一切都会完美运行,但问题是我不允许在CustomerInfo模型中进行任何更改,
有人知道我还能做些什么吗?
答案 0 :(得分:0)
有人知道我还能做些什么吗?
由于它是应该实现IDataErrorInfo接口的数据绑定属性的类,因此您需要绑定到包装CustomerInfo模型的Name属性的EditableCustomer类的属性:
<TextBox x:Name="txtName" Text="{Binding Target.NameWrapper, UpdateSourceTrigger=PropertyChanged, ValidatesOnDataErrors=True}" Width="136" HorizontalAlignment="Left"/>
internal class EditableCustomer : PropertyChangedBase, IDataErrorInfo
{
private CustomerInfo _Model;
public CustomerInfo Model
{
get { return _Model; }
set { if (_Model != value) { _Model = value; NotifyOfPropertyChange(nameof(Model)); } }
}
//bind to this one instead of binding directly to the Name property of the model:
public string NameWrapper
{
get { return _Model.Name; }
set { _Model.Name = value; NotifyOfPropertyChange(nameof(NameWrapper)); }
}
}
您必须执行此操作或使CustomerInfo类实现IDataErrorInfo接口。选择。
答案 1 :(得分:0)
使用流体验证在xaml中很容易。
public class ModelValidator : AbstractValidator<Customer>
{
public ModelValidator(){
RuleFor(model => model.Name).NotEmpty().WithMessage("Name is Requried");
RuleFor(model => model.Age).NotEmpty().WithMessage("Age is Required");
RuleFor(model => model.Designation).NotEmpty().WithMessage("Choose Your Designation");
}
}
这将有助于验证wpf。
一旦你提到fluidValidations。