开发者

How do you bind ObservableCollections to ItemsSource?

开发者 https://www.devze.com 2023-01-27 23:12 出处:网络
DataContextDataContext context1 = new DataContextDataContext(); public MainWindow() { InitializeComponent();
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 = Obs开发者_开发知识库ervableCollection<MyObject>();
    }

    private void Button_Click(object sender, RoutedEventArgs e)
    {

    }
}

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

How do you bind my ObservableCollections to the ItemsSource?


You want to set the ItemSource to the instance of an ObservableCollection you created in the constructor:

RadGridView1.ItemsSource = _MyObject;


You can make the observable collection as a public property in your code-behind/presenter/viewmodel, like

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

then you can populate that and the binding can be code code behind.

ItemsSource is a dependency property you can bind it in XAML or code behind, like suppose you want to bind to ListBox's(say named lstItems) ItemsSource, like (below code is considering that 'MyObjectCollection' is in codebehind

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

or in XAML,

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

for both the ways above you need to set the datacontext which is 'this' (for this specific solution).

But maybe you want to look into basic WPF databinding where you can understand Depedency properties, binding objects, binding modes, etc.

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/

0

精彩评论

暂无评论...
验证码 换一张
取 消