c# - 以编程方式绑定(bind) ItemsSource

标签 c# xaml binding windows-runtime

这在 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 );

最佳答案

像这样的东西应该可以工作:

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

注意:“Source = this”this 等于持有taskItemsSelectedItem

的类

关于c# - 以编程方式绑定(bind) ItemsSource,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13898654/

相关文章:

c# - 无法让 TextBlock 在 ListBox 内自动换行

c# - WPF 样式 setter 不工作

c# - 你如何在winforms中使用通用对象绑定(bind)?

c# - 如果在 C# 中的 XmlSerialization 中为 false,则隐藏 bool 值

c# - 使用 location.href 时如何获取上一页 url?

c# - Windows Phone 8.1 应用程序上的双向绑定(bind),使用 MVVM

java - 如何将属性(例如枚举)绑定(bind)到不同类型的组件属性(例如每个枚举的图像)?

c# - 从源代码编译SQLite时如何修复 "cannot find entry point sqlite3_open_v2 in DLL sqlite3"?

c# - AutoResetEvent 和 Mutex 有什么区别

c# - 如何在椭圆到达 Canvas 中间后向 Canvas 添加对象?