溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

ListBox 控件的項數(shù)據綁定與數(shù)據源變更監(jiān)聽

發(fā)布時間:2024-08-08 10:10:05 來源:億速云 閱讀:82 作者:小樊 欄目:編程語言

ListBox 控件可以通過設置 ItemsSource 屬性來綁定數(shù)據源,當數(shù)據源發(fā)生變化時,ListBox 控件會自動更新顯示的項。

要監(jiān)聽數(shù)據源的變化,可以使用 ObservableCollection 類作為數(shù)據源。ObservableCollection 類實現(xiàn)了 INotifyCollectionChanged 接口,當數(shù)據源發(fā)生變化時會觸發(fā) CollectionChanged 事件。因此,可以在 CollectionChanged 事件的處理程序中更新 ListBox 控件的顯示。

示例代碼如下:

// 創(chuàng)建一個 ObservableCollection 對象作為數(shù)據源
ObservableCollection<string> items = new ObservableCollection<string>();
items.Add("Item 1");
items.Add("Item 2");
items.Add("Item 3");

// 綁定數(shù)據源到 ListBox 控件
listBox.ItemsSource = items;

// 監(jiān)聽數(shù)據源的變化
items.CollectionChanged += Items_CollectionChanged;

// 數(shù)據源變化的處理程序
private void Items_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
    // 數(shù)據源發(fā)生變化時更新 ListBox 控件的顯示
    if (e.Action == NotifyCollectionChangedAction.Add)
    {
        foreach (string newItem in e.NewItems)
        {
            listBox.Items.Add(newItem);
        }
    }
    else if (e.Action == NotifyCollectionChangedAction.Remove)
    {
        foreach (string oldItem in e.OldItems)
        {
            listBox.Items.Remove(oldItem);
        }
    }
}

在上面的示例中,我們創(chuàng)建了一個 ObservableCollection 對象作為數(shù)據源,并綁定到 ListBox 控件上。然后我們監(jiān)聽了數(shù)據源的 CollectionChanged 事件,并在事件處理程序中更新 ListBox 控件的顯示。當數(shù)據源發(fā)生添加或移除操作時,ListBox 控件會相應地更新顯示的項。

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI