您好,登錄后才能下訂單哦!
在WPF中,ListBox控件的項(xiàng)數(shù)據(jù)綁定可以通過將ListBox的ItemsSource屬性綁定到一個(gè)集合對(duì)象來實(shí)現(xiàn)。具體步驟如下:
在ViewModel中創(chuàng)建一個(gè)ObservableCollection對(duì)象,并將需要綁定到ListBox的項(xiàng)數(shù)據(jù)添加到該集合中。
在XAML中,將ListBox的ItemsSource屬性綁定到ViewModel中的ObservableCollection對(duì)象。
<ListBox ItemsSource="{Binding Items}" />
public class ViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private ObservableCollection<string> _items;
public ObservableCollection<string> Items
{
get { return _items; }
set
{
_items = value;
OnPropertyChanged("Items");
}
}
protected void OnPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
public MainWindow()
{
InitializeComponent();
ViewModel vm = new ViewModel();
vm.Items = new ObservableCollection<string>() { "Item 1", "Item 2", "Item 3" };
DataContext = vm;
}
通過以上步驟,就可以實(shí)現(xiàn)ListBox控件的項(xiàng)數(shù)據(jù)綁定。當(dāng)ObservableCollection中的數(shù)據(jù)發(fā)生變化時(shí),ListBox中的項(xiàng)會(huì)自動(dòng)更新。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。