如何将ObservableCollections绑定到ItemsSource?

时间:2010-11-29 12:10:21

标签: c# wpf

DataContextDataContext context1 = new DataContextDataContext();
    public MainWindow()
    {
        InitializeComponent();
        DataContext = new ObservableCollection<MyObject>();
        RadGridView1.Filtered+=new EventHandler<GridViewFilteredEventArgs>(RadGridView1_Filtered);
        ObservableCollection<MyObject> _MyObject = new ObservableCollection<MyObject>();
        foreach (var p in context1.Students)
        {
            _MyObject.Add(new MyObject { ID = p.StudentID, Name = p.StudentFN });
        }
    }

    void RadGridView1_Filtered(object sender, GridViewFilteredEventArgs e)
    {
        RadGridView1.ItemsSource = ObservableCollection<MyObject>();
    }

    private void Button_Click(object sender, RoutedEventArgs e)
    {

    }
}

public class MyObject
{
    public int ID { get; set; }
    public string Name { get; set; }
}

如何将我的ObservableCollections绑定到ItemsSource?

2 个答案:

答案 0 :(得分:4)

您想将ItemSource设置为您在构造函数中创建的ObservableCollection的实例:

RadGridView1.ItemsSource = _MyObject;

答案 1 :(得分:3)

您可以在代码隐藏/演示者/视图模型中将可观察集合作为公共属性,例如

public ObservableCollection<MyObject> MyObjectCollection {get;set;}

然后你可以填充它,绑定可以是后面的代码。

ItemsSource是一个依赖属性,你可以在XAML或后面的代码中绑定它,比如假设你想绑定到ListBox(比如名为lstItems)ItemsSource,就像(在代码下面考虑'MyObjectCollection'在代码隐藏中

Binding bindingObject = new Binding("MyObjectCollection");
bindingObject.Source = this; //codebehind class instance which has MyObjectCollection
lstItems.SetBinding(ListBox.ItemsSource, bindingObject);

或在XAML中,

<ListBox x:Name="lstItems" ItemsSource="{Binding Path=MyObjectCollection}"/>

对于上述两种方法,您需要设置datacontext为'this'(针对此特定解决方案)。

但是,您可能希望了解基本的WPF数据绑定,您可以在其中了解Depedency属性,绑定对象,绑定模式等。

http://msdn.microsoft.com/en-us/library/aa480224.aspx http://msdn.microsoft.com/en-us/library/ms750612.aspx http://joshsmithonwpf.wordpress.com/2008/05/19/gradual-introduction-to-wpf-data-binding/