【问题标题】:WPF ListViewTemplate InvalidCastException: 'Unable to cast object of type 'System.Windows.Controls.ListView' to type 'System.Windows.DataTemplate'.'WPF ListViewTemplate InvalidCastException:“无法将“System.Windows.Controls.ListView”类型的对象转换为“System.Windows.DataTemplate”类型。
【发布时间】:2021-08-31 13:18:50
【问题描述】:

我想将 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# wpf listview templates


    【解决方案1】:

    错误信息很清楚。

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

    【讨论】:

      猜你喜欢
      • 2019-12-24
      • 2020-12-02
      • 2011-07-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-05
      • 1970-01-01
      相关资源
      最近更新 更多