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 ItemControl
s dependa开发者_如何学Goble 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?
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();
}
}
I think you only need one ItemsControl.
You can bind the Count to the Visibility of the ComboBoxes etc. via the same converter.
You probably just need something like this,
<ComboBox Visibility={Binding DataContext.Count, ElementName=LayoutRoot, Converter={StaticResource YourConverter}}/>
精彩评论