WPF数据表格未显示数据,但显示行

3

我正在尝试制作一个简单的WPF项目,但遇到了问题:DataGrid绑定了一个ObservableCollection,它没有显示数据,但它显示了正确的行数。以下是它的外观:

WPF DataGrid showing correct number of rows, but not showing data

这是XAML:

<Window x:Class="008.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:008"
        mc:Ignorable="d"
        Title="MainWindow">

    <StackPanel>
        <StackPanel Orientation="Horizontal" Margin="10">
            <Button Name="AddButton" HorizontalAlignment="Left"  Margin="10">Add an element</Button>
            <Button Name="DeleteOldButton" HorizontalAlignment="Left" Margin="10">Delete old files</Button>
            <Button Name="ShowPop" HorizontalAlignment="Left" Margin="10">Show most popular element</Button>
        </StackPanel>

        <DataGrid Name="dgrid" CanUserResizeColumns="True"
                  CanUserAddRows="False"
                  IsReadOnly="True"
                  DataContext="files"
                  ItemsSource="{Binding}"

                  Width="Auto">
            <DataGrid.Columns>
                <DataGridTextColumn Header="Name" Binding="{Binding Name}"/>
                <DataGridTextColumn Header="Date created" Binding="{Binding Created}"/>
                <DataGridTextColumn Header="Times Open" Binding="{Binding TimesOpen}"/>

            </DataGrid.Columns>
        </DataGrid>

    </StackPanel>
</Window>

这里是代码:

public partial class MainWindow : Window
    {
    ObservableCollection<File> files;

    public MainWindow()
    {

        InitializeComponent();
        files = new ObservableCollection<File>();
        files.Add(new File("r", DateTime.Now));
        files.Add(new File("o", DateTime.Now));
        files.Add(new File("a", DateTime.Now));
        files.Add(new File("d", DateTime.Now));

    }

}

我已经尝试将窗口的DataContext设置为文件,但没有起作用。
更新:这是File类:
class File
    {
       public string Name { get; set; }
       public DateTime Created { get; set; }
       public int TimesOpen { get; set; }

        public File(string s, DateTime d)
        {
            Created = d;
            Name = s;
            TimesOpen = 0;
        }
        public void Open()
        {
            TimesOpen++;
        }
    }

更新:已实现INotifyPropertyChanged。但没有帮助。文件定义如下:

    class File: INotifyPropertyChanged 

    {
        public event PropertyChangedEventHandler PropertyChanged;
        private string name;
        public string Name
        {
            get { return name; }
            set
            {
                if (!value.Equals(name,StringComparison.InvariantCulture)) {
                    OnPropertyChanged("Name");
                    name = value;
                }                     
            }

        }
        private DateTime created;
       public DateTime Created
        {
            get { return created; }
            set
            {
                if (!created.Equals(value))
                {
                    OnPropertyChanged("Created");
                    created = value;
                }
            }
        }
        private int times_open;
       public int TimesOpen
        {
            get { return times_open; }
            set
            {
                if (times_open != value)
                {
                    OnPropertyChanged("TimesOpen");
                    times_open = value;
                }
            }
        }

        public File(string s, DateTime d)
        {
            Created = d;
            Name = s;
            TimesOpen = 0;
        }

        void OnPropertyChanged(string name)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(name));
            }
        }

        public void Open()
        {
            TimesOpen++;
        }
    }
}

你能展示一下文件类型的定义吗? - The Sharp Ninja
是的,当然,看一下UPD。 - small-j
你尝试过让 File 实现 INotifyPropertyChanged 接口吗?将其应用于 Name、Created 和 TimeOpen 属性。 - The Sharp Ninja
看看你的异常——我看到了以下内容:System.Windows.Data Error: 40 : BindingExpression path error: 'TimesOpen' property not found on 'object' ''Char' (HashCode=7536755)'. BindingExpression:Path=TimesOpen; DataItem='Char' (HashCode=7536755); target element is 'TextBlock' (Name=''); target property is 'Text' (type 'String') - Brian Warshaw
2个回答

2

有些地方您做得不太对: - 您应该为窗口设置数据上下文
- 您的项源绑定到文件。但是,请稍等..
- 文件需要成为您数据上下文(例如主窗口)中的属性。
- 此外,您应该考虑在模型中实现INotifyPropertyChanged。

<DataGrid Name="dgrid" CanUserResizeColumns="True"
        CanUserAddRows="False"
        IsReadOnly="True"
        ItemsSource="{Binding Files}"
        Width="Auto">

    <DataGrid.Columns>
        <DataGridTextColumn Header="Name" Binding="{Binding Name}"/>
        <DataGridTextColumn Header="Date created" Binding="{Binding Created}"/>
        <DataGridTextColumn Header="Times Open" Binding="{Binding TimesOpen}"/>
    </DataGrid.Columns>
</DataGrid>

在你的代码中使用以下代码

public partial class MainWindow : Window
{
    public ObservableCollection<File> Files {get; set;}


    public MainWindow()
    {

        InitializeComponent();
        DataContext = this;
        Files = new ObservableCollection<File>();
        Files.Add(new File("r", DateTime.Now));
        Files.Add(new File("o", DateTime.Now));
        Files.Add(new File("a", DateTime.Now));
        Files.Add(new File("d", DateTime.Now));
        Files.Add(new File("d", DateTime.Now));
        Files.Add(new File("d", DateTime.Now));
    }
}

实现了INotifyPropertyChanged,尝试将DataContext设置为this和files,将files设置为公共属性-没有任何变化。 - small-j
@small-j 不,你不应该将数据上下文设置为文件。你应该在mainwindow的构造函数中将数据上下文设置为this,就像上面展示的那样。然后将ItemsSource设置为Files。你可以直接复制上面的代码,甚至不需要实现INotifyPropertyChanged就能看到网格中的数据。当你想要随后通知UI数据变化时,INotifyPropertyChanged会很有用。 - amuz
实现表格数据的类必须实现INotifyPropertyChanged接口。 - AdvApp

0

试试这个... MainWindow.xaml.cs

public partial class MainWindow : Window
{
    public MainWindow()
    {

        InitializeComponent();
        Files = new ObservableCollection<File>();
        Files.Add(new File("r", DateTime.Now));
        Files.Add(new File("o", DateTime.Now));
        Files.Add(new File("a", DateTime.Now));
        Files.Add(new File("d", DateTime.Now));
        DataContext = this;
    }
}

public ObservableCollection<File> Files { get; set; }

MainWindow.xaml(代码片段):

<DataGrid Name="dgrid" CanUserResizeColumns="True"
                  CanUserAddRows="False"
                  IsReadOnly="True"
                  ItemsSource="{Binding Files}"
                  Width="Auto">
    <DataGrid.Columns>
        <DataGridTextColumn Header="Name" Binding="{Binding Name}"/>
        <DataGridTextColumn Header="Date created" Binding="{Binding Created}"/>
        <DataGridTextColumn Header="Times Open" Binding="{Binding TimesOpen}"/>
    </DataGrid.Columns>
</DataGrid>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接