Samstag, 3. Juli 2010

Silverlight: Converter with multiple parameters

Sometimes it is necessary that you have a converter (interface IValueConverter) with multiple parameters. To reach this goal, you can use a DependencyProperty. That’s normally a very easy step, but I spend some extraordinary time with my converter becuase in my case the second parameter should be bindable

So what was the problem?

I have tried to derive the Converter from UserControl – great mistake: You have to use FrameworkElement instead!

Usage:
   1: <Helpers:StatisticsConverter x:Key="StatisticsConverter" ViewModel="{Binding ElementName=LayoutRoot,Path=DataContext.Statistics}" />
   2:     
   3: <TextBlock Margin="0,0,10,0"
   4:    FontSize="9"  
   5:    x:Name="InfoSummeText" Text="{Binding Converter={StaticResource StatisticsConverter}, ConverterParameter=Summe}" >
   6: </TextBlock>
Converter:
   1: public class StatisticsConverter : FrameworkElement, IValueConverter
   2:    {
   3:  
   4:        #region IValueConverter Members
   5:  
   6:        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
   7:        {
   8:            var statisticsViewModel = (StatisticsViewModel)ViewModel;
   9:            var statistics = statisticsViewModel.GetAnzeigeKategorieStatistics(value as AnzeigeKategorie);
  10:            switch (parameter.ToString())
  11:            {
  12:                case "Summe":
  13:                    {
  14:                        return String.Format("{0:N2}", statistics.Summe) + " EUR";
  15:                    }
  16:                default:
  17:                    {
  18:                        throw new NotImplementedException(parameter as string);
  19:                    }
  20:            }
  21:        }
  22:  
  23:        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
  24:        {
  25:            return "";
  26:        }
  27:  
  28:        #endregion
  29:  
  30:        #region object ViewModel (DependencyProperty)
  31:  
  32:        public object ViewModel
  33:        {
  34:            get { return (object)GetValue(ViewModelProperty); }
  35:            set { SetValue(ViewModelProperty, value); }
  36:        }
  37:  
  38:        public static readonly DependencyProperty ViewModelProperty =
  39:            DependencyProperty.Register(
  40:                "ViewModel",
  41:                typeof(object),
  42:                typeof(StatisticsConverter),
  43:                new PropertyMetadata(null, null));
  44:  
  45:  
  46:        #endregion ViewModel (DependencyProperty)
  47:    }

1 Kommentar:

  1. Wow great idea. I was having a problem with my ConvertBack, needing info from the ViewModel to return the correct value. This works so well.

    Thanks!

    AntwortenLöschen