10

c# 代码中的 this 等价物是什么?

<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 );
4

2 回答 2

6

像这样的东西应该工作:

BindingOperations.SetBinding(taskItemListView, ListView.DataContextProperty, new Binding("SelectedItem") { Source = itemListView});
BindingOperations.SetBinding(taskItemListView, ListView.ItemsSourceProperty, new Binding("taskItems") { Source = this });

注意:“Source = this”this等于持有taskItems,SelectedItem

于 2012-12-16T04:51:34.940 回答
1

一个简单的方法是通过 SetValue:

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

更多信息在这里:DependencyObject.SetValue 方法

于 2013-08-23T17:52:53.243 回答