简体   繁体   中英

How to bind ListboxItem as observable collection in WPF and insert new record at the Top

I have to display all the messages I am receiving from backend into a list box like

10:12:23 Login Successful.

10:13:00 Logout Successful.

How can a bind this string message as listitem with auto updation through INotifyPropertyChange and with the condition that recent item should get inserted at 0th index.

I tried this sample as follow this will help you,

View Model :

    public VM()
    {
        items = new ObservableCollection<string>();

        Items.Insert(0, "The time now is " + DateTime.Now.ToShortTimeString());
        var timer = new DispatcherTimer { Interval = TimeSpan.FromSeconds(60) };
        timer.Tick += (s, e) =>
        {
            Items.Insert(0,"The time now is " + DateTime.Now.ToShortTimeString());
        };
        timer.Start();
    }



    private ObservableCollection<string> items;

    public ObservableCollection<string> Items
    {
        get { return items; }

    }

Bind this item to XAML listview

I am quickly going to throw the code in pieces; you'll have to assemble it.

every body is using itemsource to a list which in my case is not working.

You cannot leave it as {Binding} that works if you set list's data context to collection. But if your collection is part of view-model then you must specify collection name in binding.

View :

<ListBox ItemsSource="{Binding Logs}" />
<Button Click="AddLogEntry_Click" Content="Add log entry" />

View-Model :

public class ViewModel1 : BaseViewModel
{
    private ObservableCollection<string> logs;
    public ObservableCollection<string> Logs {
        get {
            if (logs == null)
                logs = new ObservableCollection<string>();
            return logs;
        }
    }

    // This is added for test
    public void AddLogEntry() {
        Logs.Insert(0, DateTime.Now.ToString());
    }
}

View Code-Behind :

ViewModel1 vm;

public DisplayLatestItemInListbox() {
    InitializeComponent();
    vm = new ViewModel1();
    DataContext = vm;
}

// Use command instead.
private void AddLogEntry_Click(object sender, RoutedEventArgs e) {
    vm.AddLogEntry();
}

Key here is to use Insert method on ObservableCollection . And here's what you get:

在此处输入图片说明

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