Binding ItemsSource programmatically

13,374

Solution 1

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

Solution 2

An easy way to do this is by SetValue:

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

More information at here: DependencyObject.SetValue method

Share:
13,374
dcastro
Author by

dcastro

Updated on July 20, 2022

Comments

  • dcastro
    dcastro almost 2 years

    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 );
    
  • dcastro
    dcastro over 11 years
    Thanks, it works wonders! Just 2 minor corrections: the class Binding has only one constructor that takes no arguments, and turns out there was no need to set the second Binding's source. I've edited my question.
  • sa_ddam213
    sa_ddam213 over 11 years
    Binding does work with a string arg, using it now in a .NET4.0 project, link: msdn.microsoft.com/en-us/library/…
  • dcastro
    dcastro over 11 years