简体   繁体   中英

WPF: Binding ListView with collection in GridView mode. Error

So, I'm trying to bind ListView in GridView mode with my collection. Here are XAML:

<Window x:Class="MyApp.ParametersWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" mc:Ignorable="d" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" Height="340" Width="300"
    DataContext="{Binding RelativeSource={RelativeSource Self}}">
<Grid>
    <Button Content="Cancel" Height="23" HorizontalAlignment="Left" Margin="39,254,0,0" Name="button1" VerticalAlignment="Top" Width="75" />
    <Button Content="Run Test" Height="23" HorizontalAlignment="Right" Margin="0,254,51,0" Name="button2" VerticalAlignment="Top" Width="75" Click="button2_Click" />

    <ListView Height="227" HorizontalAlignment="Left" Margin="21,12,0,0" Name="listView1" VerticalAlignment="Top" Width="237"  ItemsSource="{Binding FileNames}">
        <GridView>
            <GridViewColumn Width="120" Header="Vorname" DisplayMemberBinding="{Binding Name}" />    **<!--Error in this line-->**            
        </GridView>
    </ListView>
</Grid>

Here are *.cs:

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Windows;

namespace AtmlServiceClient
{

    public partial class ParametersWindow : Window
    {
    public class FileInfo
    {
        public string Name { get; set; }
        public DateTime LastModified { get; set; }

    }

    ObservableCollection<FileInfo> mFileNames;

    public ObservableCollection<FileInfo> FileNames
    {
        get
        {
            return mFileNames;
        }
    }

    public ParametersWindow()
    {
        mFileNames = new ObservableCollection<FileInfo>();
        InitializeComponent();            
    }

    private void button2_Click(object sender, RoutedEventArgs e)
    {
        FileNames.Add(new FileInfo() {Name = "X", LastModified = DateTime.Now});
    }
}
}

I received next error when window appears. (Not when button click)

Error:

A first chance exception of type 'System.Windows.Markup.XamlParseException' occurred in PresentationFramework.dll Additional information: 'Add value to collection of type 'System.Windows.Controls.ItemCollection' threw an exception.' Line number '11' and line position '62'.

Please, help me solve it.

I think your error is in the XAML in the GridView

Try this:


The difference is that instead of

<ListView> <GridView> 

you will have

<ListView> <ListView.View> <GridView>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM