c#代码中的等价物是什么?
<ListView
x:Name="taskItemListView"
DataContext="{Binding SelectedItem, ElementName=itemListView}"
ItemsSource="{Binding taskItems}">
...
</ListView>
我已经尝试了以下代码,但它似乎无法正常工作......
Binding b = new Binding();
b.Path = new PropertyPath("taskItems");
DependencyProperty dp = DependencyProperty.Register("itemsSource", typeof(object), typeof(object), null);
BindingOperations.SetBinding(taskItemListView, dp, b);
修改:
根据@ sa_ddam213的回答,这有效:
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 );
答案 0 :(得分:5)
这样的事情应该有效:
BindingOperations.SetBinding(taskItemListView, ListView.DataContextProperty, new Binding("SelectedItem") { Source = itemListView});
BindingOperations.SetBinding(taskItemListView, ListView.ItemsSourceProperty, new Binding("taskItems") { Source = this });
注意:“来源=此”this
等于持有taskItems
,SelectedItem
答案 1 :(得分:1)
一种简单的方法是通过SetValue:
taskItemListView.SetValue(ListView.ItemsSourceProperty, this.Source);
更多信息,请点击此处:DependencyObject.SetValue method