将ObservableCollection作为ItemsControl的ItemsSource连接 [英] Attaching ObservableCollection as ItemsSource of ItemsControl

查看:149
本文介绍了将ObservableCollection作为ItemsControl的ItemsSource连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样的对象:

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,如下所示:

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 */ });

我刚刚添加的项目不会显示在ItemsControl中。我究竟在做错什么?不能弄清楚:/

感谢您的帮助。

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.

推荐答案

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

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);

这篇关于将ObservableCollection作为ItemsControl的ItemsSource连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆