Home > Blockchain >  WPF ListViewTemplate InvalidCastException: 'Unable to cast object of type 'System.Windows.
WPF ListViewTemplate InvalidCastException: 'Unable to cast object of type 'System.Windows.

Time:09-17

I want to bind an ObservableCollection to a 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;
        }

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

... and here the method content to create the ListView (it's called when you click a button)

ListView listView = new ListView();
            listView.ItemsSource = TestClass.GetTestClassCollection();
            listView.ItemTemplate = (DataTemplate)this.FindResource("ListViewTemplate");

            mainGrid.Children.Add(listView);

As soon as I click the button the application crash: Unable to cast object of type 'System.Windows.Controls.ListView' to type 'System.Windows.DataTemplate'.

I searched for some ListView templates reference, but they all seem pretty similar to mine. But obviously, something doesn't match.

The application crash on the line when I try to assign ItemTemplate.

Thanks!

CodePudding user response:

The error message is pretty clear.

(DataTemplate)this.FindResource("ListViewTemplate")

requires that the resource is a DataTemplate, but actually it is a ListView.

The resource declaration should look like this:

<Window.Resources>
    <DataTemplate x:Key="ListViewTemplate">
        <StackPanel>
            <TextBlock Text="{Binding attribute1}" />
            <TextBlock Text="{Binding attribute2}" />
            <TextBlock Text="{Binding attribute3}" />
        </StackPanel>
    </DataTemplate>
</Window.Resources>
  • Related