I'm trying to display a list of Notes. I have an ItemsControl which is bound to a collection of NoteViewModel. So in the data template of the items control I want to create a NoteControl (user control for displaying a note) and bind its ViewModel property to the NoteViewModel in the collection.
I currently have this:
<ItemsControl x:Name="itemsControl1" Grid.Row="1" ItemsSource="{Binding Notes}" >
<ItemsControl.Template>
<ControlTemplate TargetType="ItemsControl">
<ScrollViewer>
<ItemsPresenter/>
</ScrollViewer>
</ControlTemplate>
</ItemsControl.Template>
<ItemsControl.ItemTemplate>
<DataTemplate>
<uc:NoteControl uc:NoteControl.ViewModel="{Binding}"/>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
But I'm getting this exception:
System.ArgumentException: Object of type 'System.Windows.Data.Binding' cannot be converted to type 'NotePrototype.NoteViewModel'.
开发者_如何学JAVAWhat is the proper syntax for wiring this up? Is there a better technique for wiring up inner ViewModels to inner UserControls that are dynamically created/bound?
It is better to attach the ViewModel to the DataContext of you UserControl and in the usercontrol you don't need the ViewModel property, you can just bind to the implicit Datacontext because that will be you ViewModel
Extra note: To enable databinding in the designer you follow the example below:
<UserControl
<!--
all the other declaration needed are here
-->
xmlns:local="clr-namespace:NotePrototype"
d:DataContext="{DynamicResource ViewModel}"
>
<UserControl.Resources>
<local:NoteViewModel x:Key="ViewModel" d:IsDataSource="True" />
</UserControl.Resources>
<!--
put your content here
-->
</UserControl>
Edited your example for the ItemsControl:
<ItemsControl x:Name="itemsControl1" Grid.Row="1" ItemsSource="{Binding Notes}" >
<ItemsControl.Template>
<ControlTemplate TargetType="ItemsControl">
<ScrollViewer>
<ItemsPresenter/>
</ScrollViewer>
</ControlTemplate>
</ItemsControl.Template>
<ItemsControl.ItemTemplate>
<DataTemplate>
<uc:NoteControl DataContext="{Binding}"/>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
精彩评论