0

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?

4

1 回答 1

0

我不明白为什么它不应该工作。如果您将在第一次运行 - SL 将突出显示带有红色边框的 TextBox。但是,如果您尝试更改标签列表 - 您将什么也看不到,因为您在转换器中有一个错误 ConvertBack 您返回字符串类型数组 (string[]),但属性需要 List 类型的对象,所以您只需要将 ConvertBack 方法更新为:

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;
}

关于 Convert 方法的另一个注意事项,您可以使用 Join 方法:

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;
}

还有一件事是关于组合字符串。不要使用运算符 +,因为您可能会遇到性能问题,请改用 StringBuilder。

于 2012-08-17T16:27:13.150 回答