问题
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:
<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. What exactly am I doing wrong? Can't figure it out :/
Thanks for help.
回答1:
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.
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);
回答2:
Nothing wrong with your code, I tried using this... and show up on your xaml code
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; }
}
}
来源:https://stackoverflow.com/questions/19114190/attaching-observablecollection-as-itemssource-of-itemscontrol