Is there any way to convert the members of a collection used as an ItemsSource?

后端 未结 3 766
醉话见心
醉话见心 2020-12-17 15:59

In WPF you can use an IValueConverter or IMultiValueConverter to convert a data-bound value from say an int to a Color.

I have a collection

3条回答
  •  醉酒成梦
    2020-12-17 16:32

    Yes you can. It is acting the same as with the IValueConverter. You simply treat the value parameter for the Convert method as a collection.

    Here is an example of Converter for a collection:

    public class DataConvert : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            ObservableCollection convertible = null;
            var result = value as ObservableCollection;
    
            if (result != null)
            {
                convertible = new ObservableCollection();
                foreach (var item in result)
                {
                    if (item == "first")
                    {
                        convertible.Add(1);
                    }
                    else if (item == "second")
                    {
                        convertible.Add(2);
                    }
                    else if (item == "third")
                    {
                        convertible.Add(3);
                    }
                }
            }
    
            return convertible;
        }
    
        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }
    

    In this case is just a proof of concept, but I think it should show the idea very well. The Converter converts from a simple collection of strings like this:

    ModelItems = new ObservableCollection();
            ModelItems.Add("third");
            ModelItems.Add("first");
            ModelItems.Add("second");
    

    into a collection of integers corresponding to the string meaning.

    And here is the corresponding XAML (loc is the reference of the current assembly where is the converter):

    
        
    
    
        
    
    

    If you want to make a two way binding, you have to implement also the convert back. From the experience of working with MVVM, i suggest to use something like the Factory Pattern to transform from Model in ViewModel and backwards.

提交回复
热议问题