0

我有一个像这样的对象:

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

4

2 回答 2

1

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

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

// instead of lstDropOff.ItemsSource = dropOffs
var binding = new Binding() { Source = dropOffs };
lstDropOff.SetBinding(ItemsControl.ItemsSourceProperty, binding);
于 2013-10-01T10:52:48.677 回答
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; }
    }
}
于 2013-10-01T11:28:45.907 回答