【问题标题】:ObservableCollection doesn't update ListView (WPF) [duplicate]ObservableCollection 不更新 ListView (WPF) [重复]
【发布时间】:2021-11-15 03:33:42
【问题描述】:

到目前为止,我有一个简单的设置,并希望有一个显示最近日志的列表视图。

这是主窗口构造函数:

        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 确实显示“某些东西”,它具有正确数量的空行数据行?!我错过了什么? 提前致谢!!

【问题讨论】:

    标签: c# wpf listview data-binding observablecollection


    【解决方案1】:

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

    你可以做的就是改变你的班级看起来像这样:

    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?

    【讨论】:

    • 谢谢,不知道!它现在就像一个魅力
    猜你喜欢
    • 1970-01-01
    • 2014-01-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-16
    • 1970-01-01
    相关资源
    最近更新 更多