Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Binding ItemsSource programmatically

What is the equivalent of this in c# code?

<ListView
    x:Name="taskItemListView"
    DataContext="{Binding SelectedItem, ElementName=itemListView}"
    ItemsSource="{Binding taskItems}">
...
</ListView>

I've tried the following code, but it doesn't seem to work...

Binding b = new Binding();
b.Path = new PropertyPath("taskItems");

DependencyProperty dp = DependencyProperty.Register("itemsSource", typeof(object), typeof(object), null);
BindingOperations.SetBinding(taskItemListView, dp, b);

Edit:

Based on @sa_ddam213's answer, this worked:

Binding dataContextBinding = new Binding();
dataContextBinding.Path = new PropertyPath("SelectedItem");
dataContextBinding.Source = itemListView;
BindingOperations.SetBinding(taskItemListView, ListView.DataContextProperty, dataContextBinding );

Binding sourceBinding = new Binding();
sourceBinding.Path = new PropertyPath("taskItems");
BindingOperations.SetBinding(taskItemListView, ListView.ItemsSourceProperty, sourceBinding );
like image 626
dcastro Avatar asked Dec 16 '12 04:12

dcastro


2 Answers

Somthing like this should work:

BindingOperations.SetBinding(taskItemListView, ListView.DataContextProperty, new Binding("SelectedItem") { Source = itemListView});
BindingOperations.SetBinding(taskItemListView, ListView.ItemsSourceProperty, new Binding("taskItems") { Source = this });

Note: "Source = this" this equals the class that is holding the taskItems, SelectedItem

like image 128
sa_ddam213 Avatar answered Oct 21 '22 07:10

sa_ddam213


An easy way to do this is by SetValue:

taskItemListView.SetValue(ListView.ItemsSourceProperty, this.Source);

More information at here: DependencyObject.SetValue method

like image 41
Rodrigo T. Avatar answered Oct 21 '22 08:10

Rodrigo T.