Mega Code Archive

 
Categories / C# / Data Types
 

Converts a collection of tags to a single string representation containing the tags separated by a comma

using System; using System.Collections.ObjectModel; using System.Globalization; using System.Text; using System.Windows.Data; namespace Photoviewer.Common {     /// <summary>     /// Specialized converter to convert between a tag collection     /// and a string representation of the tags     /// </summary>     public class TagsValueConverter : IValueConverter     {         #region IValueConverter Members         /// <summary>         /// Converts a collection of tags to a single string representation         /// containing the tags separated by a comma         /// </summary>         /// <param name="value"></param>         /// <param name="targetType"></param>         /// <param name="parameter"></param>         /// <param name="culture"></param>         /// <returns></returns>         public object Convert(object value, Type targetType, object parameter, CultureInfo culture)         {             if (!(value is Collection<string>))             {                 return null;             }             StringBuilder outputBuilder = new StringBuilder();             bool first = true;             foreach (string item in (Collection<string>)value)             {                 if (!first)                 {                     outputBuilder.Append(", ");                 }                 outputBuilder.Append(item);                 first = false;             }             return outputBuilder.ToString();         }         /// <summary>         /// Converts a set of tags separated by a comma back to         /// a collection of tags         /// </summary>         /// <param name="value"></param>         /// <param name="targetType"></param>         /// <param name="parameter"></param>         /// <param name="culture"></param>         /// <returns></returns>         public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)         {             string[] parts = value.ToString().Split(',');             Collection<string> tags = new Collection<string>();             foreach (string tag in parts)             {                 tags.Add(tag.Trim());             }             return tags;         }         #endregion     } }