将ObservableCollection附加为ItemsControl的ItemsSource

时间:2013-10-01 10:45:17

标签: c# wpf xaml data-binding observablecollection

我有一个像这样的对象:

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中。我究竟做错了什么?无法弄清楚:/
谢谢你的帮助。

2 个答案:

答案 0 :(得分:1)

您尚未使用绑定设置ItemsSource,您需要执行此操作才能涉及WPF绑定引擎并让控件对数据源更改做出反应。

以下是如何从代码隐藏中做到这一点:

// instead of lstDropOff.ItemsSource = dropOffs
var binding = new Binding() { Source = dropOffs };
lstDropOff.SetBinding(ItemsControl.ItemsSourceProperty, binding);

答案 1 :(得分:0)

您的代码没有问题,我尝试使用此...并显示您的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; }
    }
}