Tương đương với điều này trong mã C# là gì?Các mục ràng buộcSource theo lập trình
<ListView
x:Name="taskItemListView"
DataContext="{Binding SelectedItem, ElementName=itemListView}"
ItemsSource="{Binding taskItems}">
...
</ListView>
Tôi đã thử đoạn code sau, nhưng nó dường như không làm việc ...
Binding b = new Binding();
b.Path = new PropertyPath("taskItems");
DependencyProperty dp = DependencyProperty.Register("itemsSource", typeof(object), typeof(object), null);
BindingOperations.SetBinding(taskItemListView, dp, b);
Sửa:
Dựa trên câu trả lời @ sa_ddam213, điều này làm việc:
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);
Cảm ơn, nó hoạt động kỳ diệu! Chỉ cần 2 sửa đổi nhỏ: lớp Binding chỉ có một hàm tạo không có đối số, và hóa ra không cần thiết lập nguồn Binding thứ hai. Tôi đã chỉnh sửa câu hỏi của mình. – dcastro
Ràng buộc không hoạt động với một chuỗi arg, sử dụng nó ngay bây giờ trong một dự án .NET4.0, liên kết: http://msdn.microsoft.com/en-us/library/system.windows.data.binding.aspx –
Không bật một ứng dụng WinRT: http://msdn.microsoft.com/en-us/library/windows/apps/br209820.aspx#constructors. – dcastro