[英]Attaching ObservableCollection as ItemsSource of ItemsControl
I have an object like so: 我有一个像这样的对象:
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 */
}
Now in my MainWindow.xaml I have an ItemsControl like so: 现在在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>
I bind the data to this list in my code behind like so: 我将数据绑定到我后面的代码中的此列表中,如下所示:
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 */ });
The items I have just added do not show in the ItemsControl. 我刚刚添加的项目未显示在ItemsControl中。 What exactly am I doing wrong? 我到底在做什么错? Can't figure it out :/ 无法解决:/
Thanks for help. 感谢帮助。
You have not set the ItemsSource
using a binding, which you need to do in order to involve the WPF binding engine and have the control react to data source changes. 您尚未使用绑定设置ItemsSource
,需要进行此操作才能涉及WPF绑定引擎并使控件对数据源更改做出反应。
Here's how to do that from code-behind: 这是从背后的代码中做到的:
// instead of lstDropOff.ItemsSource = dropOffs
var binding = new Binding() { Source = dropOffs };
lstDropOff.SetBinding(ItemsControl.ItemsSourceProperty, binding);
Nothing wrong with your code, I tried using this... and show up on your xaml code 您的代码没问题,我尝试使用此代码...并显示在您的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.