我有3个数据模板的列表视图。我应该使用什么来将模板分配给传入的item - ItemTemplateSelector或附加到listview的ChoosingItemContainer事件?
到目前为止,我一直在使用ItemTemplateSelector,但当我快速滚动列表时,它会给出一个异常,可能是因为虚拟化。自动生成尝试将首先添加的项类型转换为当前添加的项的数据类型。你能解释这种行为吗?
这是我面临的问题的一个虚拟版本
public class Person
{
public PersonType Type;
public string Name;
}
public enum PersonType
{
Employee, Student, Manager
}
public class Employee : Person
{
public string Id;
}
public class Student : Person
{
public string CollegeName;
}
public class Manager : Person
{
public string Level;
}在MainPage.xaml中,我有以下DataTemplates和ItemTemplateSelector
<DataTemplate x:Key="EmployeeTemplate" x:DataType="local:Employee">
<StackPanel Orientation="Horizontal" Background="Bisque">
<TextBlock Text="{x:Bind Name}" Margin="10,0"/>
<TextBlock Text="{x:Bind Id}" Margin="10,0"/>
</StackPanel>
</DataTemplate>
<DataTemplate x:Key="StudentTemplate" x:DataType="local:Student">
<RelativePanel Background="Aqua">
<TextBlock x:Name="NameBlock" Text="{x:Bind Name}" Margin="10,0"/>
<TextBlock RelativePanel.RightOf="NameBlock" Text="{x:Bind CollegeName}" Margin="10,0"/>
</RelativePanel>
</DataTemplate>
<DataTemplate x:Key="ManagerTemplate" x:DataType="local:Manager">
<Grid Background="BurlyWood">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
<TextBlock Text="{x:Bind Name}" Margin="10,0"/>
<TextBlock Grid.Column="1" Text="{x:Bind Level}" Margin="10,0"/>
</Grid>
</DataTemplate>
<local:ListViewItemTemplateSelector x:Key="ItemTemplateSelector"
EmployeeTemplate="{StaticResource EmployeeTemplate}"
StudentTemplate="{StaticResource StudentTemplate}"
ManagerTemplate="{StaticResource ManagerTemplate}"/>当我快速浏览列表时,我在MainPage.g.cs中得到了一个异常
public void DataContextChangedHandler(global::Windows.UI.Xaml.FrameworkElement sender, global::Windows.UI.Xaml.DataContextChangedEventArgs args)
{
global::TestApp.Employee data = args.NewValue as global::TestApp.Employee;
if (args.NewValue != null && data == null)
{
throw new global::System.ArgumentException("Incorrect type passed into template. Based on the x:DataType global::TestApp.Employee was expected.");
}
this.SetDataRoot(data);
this.Update();
}在这里,args.newValue包含一个学生项目,它位于列表的中间。
发布于 2016-10-28 01:19:30
此异常不是致命的- Visual Studio捕获所有“已启用”的异常。
如果您想避免抛出它,当ListItemView的内容与虚拟化机制为单元格指定的内容不同时,将其设置为null:
protected override DataTemplate SelectTemplateCore(
object itemViewModel,
DependencyObject container)
{
var itemView = container as ListViewItem;
if (itemView != null) {
var content = itemView.Content;
if (content != null && content.GetType() != itemViewModel.GetType()) {
itemView.Content = null;
}
}
... // return DataTemplate for itemViewModel
}https://stackoverflow.com/questions/40108792
复制相似问题