c# - WPF ListViewTemplate InvalidCastException:“无法将“System.Windows.Controls.ListView”类型的对象转换为“System.Windows.DataTemplate”类型。
问题描述
我想将 ObservableCollection 绑定到 ListView。
class TestClass
{
public string attribute1 { get; set; }
public string attribute2 { get; set; }
public string attribute { get; set; }
}
static public ObservableCollection<TestClass> GetTestClassCollection()
{
SpecialObjects[] specialobject = Class.GetSpecialObjects();
ObservableCollection<TestClass> specialTestObjects = new ObservableCollection<TestClass>();
foreach (SpecialObject special in specialobject)
{
specialTestObjects.Add(new TestClass() { attribute1 = special.attribute1, attribute2 = special.attribute2, attribute3 = special.attribute3 });
}
return specialTestObjects;
}
我的 MainWindow.xaml
<!-- Data Template -->
<Window.Resources>
<ListView x:Key="ListViewTemplate">
<ListView.ItemTemplate>
<DataTemplate>
<StackPanel>
<TextBlock Text="{Binding attribute1}" />
<TextBlock Text="{Binding attribute2}" />
<TextBlock Text="{Binding attribute3}" />
</StackPanel>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</Window.Resources>
...这里是创建 ListView 的方法内容(单击按钮时会调用它)
ListView listView = new ListView();
listView.ItemsSource = TestClass.GetTestClassCollection();
listView.ItemTemplate = (DataTemplate)this.FindResource("ListViewTemplate");
mainGrid.Children.Add(listView);
一旦我单击按钮,应用程序就会崩溃:
Unable to cast object of type 'System.Windows.Controls.ListView' to type 'System.Windows.DataTemplate'.
我搜索了一些 ListView 模板参考,但它们看起来都与我的非常相似。但很明显,有些东西不匹配。
当我尝试分配 ItemTemplate 时,应用程序在线崩溃。
谢谢!
解决方案
错误信息非常清楚。
(DataTemplate)this.FindResource("ListViewTemplate")
要求资源是 DataTemplate,但实际上它是 ListView。
资源声明应如下所示:
<Window.Resources>
<DataTemplate x:Key="ListViewTemplate">
<StackPanel>
<TextBlock Text="{Binding attribute1}" />
<TextBlock Text="{Binding attribute2}" />
<TextBlock Text="{Binding attribute3}" />
</StackPanel>
</DataTemplate>
</Window.Resources>
推荐阅读
- razor - 在 mvc 中有两列的 Razor 表
- python - 无法从 Api 动态访问具有重复值的字典 - Python for Binance
- laravel - 多个 if/else 语句是 laravel 不适合我
- node.js - node.js 添加点击事件
- ubuntu - 如果服务器返回 404,则 proxy_pass 到备用服务器
- android - Android BLE 在三星 Galaxy S8+ 上找不到特定设备
- batch-file - 将当前文件名从循环传递到批处理脚本中的标签
- pandas - 何时需要在 Pandas 数据框操作中指定就地参数
- python - 安装 textract 时出现错误
- excel - Excel将两列中的数字与第三列中的数字匹配