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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With