views:

39

answers:

1

I create class with two property - name,link(below). I use simple property validation by Required and StringLength attribute. I bind this class object to WPF ListBox(with textBoxs).

But when I have textbox empty or write words longer than 8 sign nothing happens :/

What should I do to fires ErrorMessage? Or how to implement validation in other way ?

I also try use :

            if (value is int)
            {
                throw new ArgumentException("Wpisałeś stringa!!");
            }

But it only fires in debug mode :/

My class with implementation of attribute validation:

 public class RssInfo : INotifyPropertyChanged
{
    public RssInfo() { }
    public RssInfo(string _nazwa, string _link)
    {
        nazwa = _nazwa;
        link = _link;
    }

    private string nazwa;
    [Required(ErrorMessage = "To pole jest obowiązkowe nAZWA")]
    public string Nazwa
    {
        get { return nazwa; }
        set
        {
            if (value != nazwa)
            {
                nazwa = value;
                onPropertyChanged("Nazwa");
            }
            if (value is int)
            {
                throw new ArgumentException("Wpisałeś stringa!!");
            }
        }
    }
    private string link;
    [Required(ErrorMessage="To pole jest obowiązkowe link")]
    [StringLength(8, ErrorMessage = "Link cannot be longer than 8 characters")]
    public string Link
    {
        get { return link; }
        set
        {
            if (value != link)
            {
                link = value;
                onPropertyChanged("Link");
            }
        }
    }

    #region INotifyPropertyChanged Members

    public event PropertyChangedEventHandler PropertyChanged;

    #endregion

    private void onPropertyChanged(string propertyName)
    {

        if (this.PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}
+1  A: 

Is your TextBox TextProperty binded to your Name RSSInfo Property ? And is the binding mode TwoWays ? Also, remember that a Text binding in a TextBox is only updated when the TextBox loses keyboard focus. If you want to update the property on each keyboard input, use the UpdateSourceTrigger="PropertyChanged" attribute in the binding.

Show us your XAML too, the answer can be really simple ;-)

Also, I would suggest you to enhance your validation by using a custom ValidationRule on your TextBox. This will enable your UI to only present valid datas your model (RSSInfo) Name and Link properties, because a TextBox ValidationRule disables the Text binding when the user input is invalid. That's a must use ;-)

More information on ValidationRule here : http://weblogs.asp.net/monikadyrda/archive/2009/06/24/wpf-textbox-validation.aspx

Aurélien Ribon
You help me so much!! Post from link are also so useful :) Monika - whom blog it is, is also from my country, but I never hear about her blog, thanks! :)
netmajor