Home > database >  ObservableCollection doesn't update ListView (WPF) [duplicate]
ObservableCollection doesn't update ListView (WPF) [duplicate]

Time:09-22

I have a simple setup so far and want to have a listview showing the recent logs.

This is the mainwindow constructor :

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

        DataContext = MWViewModel;

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

        InitializeComponent();

        MWViewModel.updateLogs();

    }

The logging works fine. In the Viewmodel it looks like this :

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();
    }

The getLogs function also works fine, meaning the _logs have all the logging entries of the database.

The XAML looks like this :

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

Finally, the Model looks like this

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

Quite simple, but it doesn't work so far. The ListView does show "something", it has the correct amount of datarows with empty lines?! What am I missing? Thanks in advance!!

CodePudding user response:

WPF doesn't support data binding to fields. Use properties instead.

What you can do is change your class to look like this:

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

For more info -> Why does WPF support binding to properties of an object, but not fields?

  • Related