ObservableCollection 不更新 ListView (WPF)

ObservableCollection doesn't update ListView (WPF)

到目前为止,我的设置很简单,想要一个显示最近日志的列表视图。

这是主窗口构造函数:

        public MainWindow()
    {
        var MWViewModel = new ViewModel.MainWindowViewModel();

        DataContext = MWViewModel;

        Tools.Logger.LogEntry("Initialized", "Boot", "Welcome");

        InitializeComponent();

        MWViewModel.updateLogs();

    }

日志记录工作正常。 在 Viewmodel 中它看起来像这样:

class MainWindowViewModel : ViewModelBase
{
    public ObservableCollection<Models.LogModel> _logs;
    public ObservableCollection<Models.LogModel> Logs      
    {
        get => _logs;
        set => SetProperty(ref _logs, value);
    }

    public void updateLogs()
    {
        _logs = Tools.Logger.getLogs();
    }

getLogs 函数也可以正常工作,这意味着 _logs 具有数据库的所有日志记录条目。

XAML 看起来像这样:

                    <ListView x:Name="logs_viw" ItemsSource="{Binding Logs}">
                    <ListView.View >
                        <GridView>
                            <GridViewColumn Width="120" Header="Timestamp" DisplayMemberBinding="{Binding timestamp}"/>
                            <GridViewColumn Width="120" Header="Program" DisplayMemberBinding="{Binding program}"/>
                            <GridViewColumn Width="120" Header="Section" DisplayMemberBinding="{Binding section}"/>
                            <GridViewColumn Width="610" Header="Log" DisplayMemberBinding="{Binding log}"/>
                        </GridView>
                    </ListView.View>
                </ListView>

最后模型是这样的

    class LogModel
{
    public string timestamp;
    public string program;
    public string section;
    public string log;
}

很简单,但目前还行不通。 ListView 确实显示“某物”,它有正确数量的空行数据行?!我错过了什么? 提前致谢!!

WPF 不支持数据绑定到字段。请改用属性。

您可以将 class 更改为如下所示:

class LogModel
{
    public string Timestamp { get; set; }
    public string Program { get; set; }
    public string Section { get; set; }
    public string Log { get; set; }
}

了解更多信息 -> Why does WPF support binding to properties of an object, but not fields?