2 回答
![?](http://img1.sycdn.imooc.com/533e4cf4000151f602000200-100-100.jpg)
TA贡献1863条经验 获得超2个赞
这里有一个使用的例子DataTemplateSelector......
这里有一个简单的ViewModel:
public class YourCustomObject : INotifyPropertyChanged
{
public string YourProperty { get; set; } // Remember to rise propertychanged
public event PropertyChangedEventHandler PropertyChanged;
}
public class YourViewModel
{
public ObservableCollection<YourCustomObject> Objects { get; set; }
}
定义要使用的不同模板:
<ItemsControl ItemsSource="{Binding Objects}" Name="ListNormal" Margin="4,0">
<ItemsControl.Resources>
<DataTemplate x:Key="firstDataTemplate">
<UserControl1 />
</DataTemplate>
<DataTemplate x:Key="otherDataTemplate">
<UserControl2 />
</DataTemplate>
</ItemsControl.Resources>
创建一个继承自的类DataTemplateSelector:
public class MySelector : DataTemplateSelector
{
public override DataTemplate SelectTemplate(object item, DependencyObject container)
{
FrameworkElement element = container as FrameworkElement;
if (element != null && item != null && item is YourCustomObject)
{
YourCustomObject taskitem = item as YourCustomObject;
// HERE i'm putting the custom logic for choosing the correct template
if (taskitem.YourProperty == "Value 1")
return
element.FindResource("firstDataTemplate") as DataTemplate;
else
return
element.FindResource("otherDataTemplate") as DataTemplate;
}
return null;
}
}
将选择器的一个实例添加到您的主视图中:
<Window.Resources>
<local:MySelector x:Key="Selector"/>
</Window.Resource>
将的ItemTemplateSelector属性设置ItemsControl为 Selector:
<ItemsControl ItemsSource="{Binding Objects}" Name="ListNormal" Margin="4,0" ItemTemplateSelector="{StaticResource Selector}">
![?](http://img1.sycdn.imooc.com/54584ed2000152a202200220-100-100.jpg)
TA贡献1869条经验 获得超4个赞
通常这样做的方法是使用 DataTemplates。从ObservableCollection<object> Objects您的 ViewModel 中的an 开始...它不一定是<object>,如果您愿意,它可以是一些常见的基类。然后在您的 XAML 中为每种类型添加 DataTemplates。我把它们放在ItemsControl.Resources这里,但你可以把它们放在UserControl.Resources你觉得合适的地方:
<ItemsControl>
<ItemsControl.Resources>
<DataTemplate DataType="{x:Type viewmodels:YourViewModel1}">
<views:UserControl1 />
</DataTemplate>
<DataTemplate DataType="{x:Type viewmodels:YourViewModel2}">
<views:UserControl2 />
</DataTemplate>
... etc ...
还要删除<ItemsControl.ItemTemplate>标签,因为如果不这样做,它只会覆盖 DataTemplates。
这就是你需要做的!每次有一个类型的对象时YourViewModel1,Objects它都会与 UserControl1 一起显示,并且对于您指定的所有其他模板也是如此。
- 2 回答
- 0 关注
- 743 浏览
添加回答
举报