Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# - Silverlight - ItemControl, conditional item template

I have an item controller which I bind to ObservableCollection<User>. I ran into an issue where when there is only one user I would like to show a different ItemTemplate (just the Rating for example - and use default for everything else) and if there are more I would like to let people edit a bit more about them - combo box etc.

I though that probably there is a way of using converter for this, however I'm not sure how I can use converter to pick either one or another. So far I have managed to write a converter to hide/show two separate ItemControls dependable on Count of ObservableCollection<User> property. However, I don't think this is the best way of solving this problem.

Are there better ways of solving this?

like image 686
Luke Avatar asked Jun 16 '26 08:06

Luke


1 Answers

You need only one ItemsControl with template selection:

 <ItemsControl ItemsSource="{Binding Users}" ItemTemplate="{Binding Users.Count, Converter={StaticResource UserTemplateSelector}"/>

where

    public class UserTemplateSelector : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            int userCount = (int) value;
            if (userCount == 1)
            {
                return (DataTemplate) Application.Current.Resources["SingleUserTemplate"]; //SingleUserTemplate should be created e.g. in App.xaml
            }

            return (DataTemplate)Application.Current.Resources["MultipleUserTemplate"]; //MultipleUserTemplate should be created e.g. in App.xaml
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotSupportedException();
        }
    }
like image 137
Vladimir Dorokhov Avatar answered Jun 18 '26 22:06

Vladimir Dorokhov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!