开发者

Validation Error messages in silverlight MVVM

I'm attempting to implement the technique for data validation from Josh Smith's example here: Using a viewmodel to provide meaningful validation...

My code is remarkably similar to the example, except for a few difference, namely I'm using the MVVM-Light toolkit, and my model person class is a partial class that comes from a WCF backend.

Here's an example of the code in question:

First is the Automatically generated version of the class which comes from the WCF:

public partial class Person : BaseObject
{
    private string FooField;
    public string Foo {
        get {
                return this.FooField;
            }
        set {
                if ((object.ReferenceEquals(this.FooField, value) != true)) {
                    this.FooField = value;
                    this.RaisePropertyChanged("Foo");
                }
            }
}

I then extend the partial class to implement IDataErrorInfo:

public partial class Person : IDataErrorInfo
{

    public string Error
    {
        get { return null;}
    }

    public string this[string propertyName]
    {
        if (propertyName == "Foo")
        {
            //Do some backend Validation
        }
    }
}

And lastly I have a viewmodel:

public class PersonViewModel : INotifyProperyChanged, IDataErrorInfo
{
    private string _fooString;
    private Person _person;

    ...

    public string Foo {
        get { return _fooString; }
        set 
        {
            if (value == _fooString;)
                return;

            _fooString = v开发者_如何学运维alue;

            RaisePropertyChanged("Foo");
        }

    public string this[string propertyName]
    {
        if (propertyName == "Foo")
        {
            string msg = Validate(Foo);  //Frontend Validation, range, format, etc.
            if(msg ! = null)
                return msg;

            _person.Foo = Foo;

        }
    }
}

So when I bind to the property in the viewmodel the validation code defined in IDataErrorInfo's indexer gets executed on the view model and my textbox or whatever gets highlighted if my validation fails, as expected. However in my code the Indexer on the MODEL side never gets executed, at all. I can honestly say that I don't see or understand the mechanism that is supposed to invoke it. I have run the example code from Josh Smith's example, and it does work, calling the MV's this[], then if validation passes the Model's this[] hits for additional validation, but I for the life of me can't see how it happens.

I really hope this is something simple I'm overlooking. Thanks for looking at it.


You are missing

return _person[propertyName];

from the the indexer in the ViewModel.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜