首页 > 解决方案 > 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 时,应用程序在线崩溃。

谢谢!

标签: c#wpflistviewtemplates

解决方案


错误信息非常清楚。

(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>

推荐阅读