我有一个绑定(bind)到 ObservableCollection<User>
的项目 Controller .
我遇到了一个问题,当只有一个用户时我想显示不同的 ItemTemplate
(例如,仅评级 - 其他所有内容均使用默认值)如果还有更多,我想让人们对其进行更多编辑 - 组合框等。
我虽然可能有一种为此使用转换器的方法,但是我不确定如何使用转换器来选择一个或另一个。到目前为止,我已经设法编写了一个转换器来隐藏/显示 两个 分开的 ItemControl
依赖 Count
的 ObservableCollection<User> property
.但是,我认为这不是解决此问题的最佳方法。
有没有更好的方法来解决这个问题?
最佳答案
您只需要一个带有模板选择的 ItemsControl:
<ItemsControl ItemsSource="{Binding Users}" ItemTemplate="{Binding Users.Count, Converter={StaticResource UserTemplateSelector}"/>
在哪里
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();
}
}
关于C# - Silverlight - ItemControl,条件项模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7411492/