![](/img/trans.png)
[英]How to bind one ObservableCollection as ItemsSource to different comboBoxes (models) if using wpf ItemsControl with MVVM pattern?
[英]Attaching ObservableCollection as ItemsSource of ItemsControl
我有一個像這樣的對象:
class RCLocation : INotifyPropertyChanged
{
private string _id;
private string _name;
private bool _checked;
public string Id { /* get/set with NotifyPropertyChanged() */ }
public string Name { /* get/set with NotifyPropertyChanged() */ }
public bool Checked { /* get/set with NotifyPropertyChanged() */ }
/* INotifyPropertyChanged implementation methods */
}
現在在MainWindow.xaml中,有一個ItemsControl像這樣:
<ItemsControl Name="lstDropOff" ScrollViewer.VerticalScrollBarVisibility="Auto">
<ItemsControl.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<CheckBox IsChecked="{Binding Checked, Mode=TwoWay}"/>
<TextBlock Text="{Binding Name}"/>
</StackPanel>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
我將數據綁定到我后面的代碼中的此列表中,如下所示:
ObservableCollection<RCLocation> dropOffs = new ObservableCollection<RCLocation>();
lstDropOff.ItemsSource = dropOffs;
dropOffs.Add(new RCLocation { /* some data here */ });
dropOffs.Add(new RCLocation { /* some data here */ });
dropOffs.Add(new RCLocation { /* some data here */ });
dropOffs.Add(new RCLocation { /* some data here */ });
我剛剛添加的項目未顯示在ItemsControl中。 我到底在做什么錯? 無法解決:/
感謝幫助。
您尚未使用綁定設置ItemsSource
,需要進行此操作才能涉及WPF綁定引擎並使控件對數據源更改做出反應。
這是從背后的代碼中做到的:
// instead of lstDropOff.ItemsSource = dropOffs
var binding = new Binding() { Source = dropOffs };
lstDropOff.SetBinding(ItemsControl.ItemsSourceProperty, binding);
您的代碼沒問題,我嘗試使用此代碼...並顯示在您的xaml代碼中
using PhoneApp4.Resources;
using System.ComponentModel;
using System.Collections.ObjectModel;
using Microsoft.Phone.Controls;
namespace PhoneApp4
{
public partial class MainPage : PhoneApplicationPage
{
public MainPage()
{
InitializeComponent();
ObservableCollection<RCLocation> dropOffs = new ObservableCollection<RCLocation>();
lstDropOff.ItemsSource = dropOffs;
dropOffs.Add(new RCLocation { Id = "1", Name = "Tester", Checked = true });
dropOffs.Add(new RCLocation { Id = "1", Name = "Tester", Checked = true });
dropOffs.Add(new RCLocation { Id = "1", Name = "Tester", Checked = true });
dropOffs.Add(new RCLocation { Id = "1", Name = "Tester", Checked = true });
}
}
class RCLocation
{
private string _id;
private string _name;
private bool _checked;
public string Id { get; set; }
public string Name { get; set; }
public bool Checked { get; set; }
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.