c# – 以编程方式绑定ItemsSource

前端之家收集整理的这篇文章主要介绍了c# – 以编程方式绑定ItemsSource前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
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的类

猜你在找的C#相关文章