简体   繁体   中英

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

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

An easy way to do this is by SetValue:

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

More information at here: DependencyObject.SetValue method

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM