2012-12-16 11 views
6

Was ist das Äquivalent in C# -Code?Binding ItemsSource programmgesteuert

<ListView 
    x:Name="taskItemListView" 
    DataContext="{Binding SelectedItem, ElementName=itemListView}" 
    ItemsSource="{Binding taskItems}"> 
... 
</ListView> 

Ich habe den folgenden Code versucht, aber es scheint nicht zu funktionieren ...

Binding b = new Binding(); 
b.Path = new PropertyPath("taskItems"); 

DependencyProperty dp = DependencyProperty.Register("itemsSource", typeof(object), typeof(object), null); 
BindingOperations.SetBinding(taskItemListView, dp, b); 

bearbeiten:

Basierend auf @ sa_ddam213 Antwort, dies gearbeitet:

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

Antwort

4

So etwas sollte funktionieren:

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

Hinweis: "Source = this" this entspricht der Klasse, die die taskItems hält, SelectedItem

+0

Danke, es funktioniert Wunder! Nur zwei kleinere Korrekturen: Die Klasse Binding hat nur einen Konstruktor, der keine Argumente annimmt, und es stellt sich heraus, dass die zweite Binding-Quelle nicht gesetzt werden musste. Ich habe meine Frage bearbeitet. – dcastro

+0

Bindung funktioniert mit einem String Arg, verwenden Sie es jetzt in einem .NET4 Projekt, Link: http://msdn.microsoft.com/en-us/library/system.windows.data.binding.aspx –

+0

Nicht auf eine WinRT-App: http://msdn.microsoft.com/en-us/library/windows/apps/br209820.aspx#constructors. – dcastro

0

Eine einfache Möglichkeit, dies durch SetValue ist zu tun:

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

Weitere Informationen unter hier : DependencyObject.SetValue method