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),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 );
解决方法
这样的事情应该有效:
BindingOperations.SetBinding(taskItemListView,new Binding("SelectedItem") { Source = itemListView}); BindingOperations.SetBinding(taskItemListView,new Binding("taskItems") { Source = this });
注意:“Source = this”这等于持有taskItems,SelectedItem的类