Question

I have a class with a List<string> Tags that I want to display in a TextBox. For this I use a IValueConverter.

ListToStringConverter:

public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
    var list = value as List<string>;
    var returnvalue = string.Empty;

    if(list != null)
        list.ForEach(item => returnvalue += item + ", ");
    return returnvalue;
}

public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
    var strValue = value as string;

    if(strValue != null)
        return strValue.Split(new char[] { ',' });

    return null;
}

Class Test:

public class Test : IDataErrorInfo
{
    public Test()
    {
        Tags = new List<string>();
    }

    public List<string> Tags { get; set; }

    string errors;
    const string errorsText = "Error in Test class.";
    public string Error
    {
        get { return errors; }
    }

    public string this[string propertyName]
    {
        get 
        {
            errors = null;
            switch (propertyName)
            {
                case "Tags":
                    if (Tags.Count <= 1)
                    {
                        errors = errorsText;
                        return "...more tags plz..";
                    }
                    break;
            }
            return null;
        }
    }
}

Now I want to Validate the Tags:

<TextBox Text="{Binding Test.Tags, Converter={StaticResource ListToStringConverter}, Mode=TwoWay, ValidatesOnDataErrors=True}" />

But there is no error displayed. Maybe because of the conversion but how can i still accomplish a validation?

Was it helpful?

Solution

I don't see why it shouldn't work. If you will run this at first time - SL will highlight the TextBox with red border. But if you will try to change the list of tags - you will see nothing, because you in your converter you have a bug in ConvertBack you return type array of strings (string[]), but property expects object with type List, so you just need to update the ConvertBack method to:

public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
    var strValue = value as string;

    if (strValue != null)
        return strValue.Split(new char[] { ',' }).ToList();

    return null;
}

One more note about Convert method, you can use Join method:

public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
    var list = value as List<string>;
    if (list != null)
        return String.Join(", ", list);
    return null;
}

And one more thing about combining the strings. Don't use operator +, because you can have performance issues with it, use StringBuilder instead.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top