Binding to an MVVM Light relay command inside of a Windows Phone 7 item data template
I'm attempting to bind a button to a viewmodel command using MVVM Light commands, and for some reason the command doesn't seem to be getting called. Normally I don't have any issues using commands, but this one seems to be ignoring the binding.
Here's my code:
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel>
<Button>
<Interactivity:Interaction.Triggers>
<Interactivity:EventTrigger EventName="Click">
<Command:EventToCommand
Command="{Binding MyButtonClickAction}" />
</Interactivity:EventTrigger>
</Interactivity:Interaction.Triggers>
</Button>
<StackPanel>
<TextBlock Text="{Binding MyProperty}"/>
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding MyOtherProperty}" />
</StackPanel>
</StackPanel>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
This data template is in a list that gets created after my app launches, and I'm wondering开发者_运维问答 if that's the problem. My theory is that the view model is created and the constructor attempts to set up the binding with the relay command, but since the list doesn't have any items yet, the binding fails somehow.
The bindings to MyProperty and MyOtherProperty work fine.
Any suggestions as to how I might get this working?
The problem is that inside a DataTemplate, the DataContext is the item itself, not your ViewModel. So when you say {Binding MyButtonActionClick}
, the binding is looking for a command called MyButtonActionClick
on the item, which I'm guessing is just a simple object and doesn't have command properties of its own.
There are a couple of ways to get around this. Since you're already using MMVM Light the best approach might be to define your collection as List<FooViewModel>
rather than List<Foo>
and wrap your items in a ViewModel class of their own. Then you can add a MyButtonActionClick
command to that ViewModel and the call back to the parent ViewModel.
Otherwise, change your command binding so it looks at the DataContext of the ItemsControl itself. Take a look at this question (and the accepted answer, of course) for some ideas on how to do that.
As a side note, you may want to consider using the ButtonBaseExtensions class when associating commands with your buttons. This class can be found in the GalaSoft.MvvmLight.Command namespace in the GalaSoft.MvvmLight.WP7 assembly.
Your namespace XAML would then include :-
xmlns:cmd="clr-namespace:GalaSoft.MvvmLight.Command;assembly=GalaSoft.MvvmLight.WP7"
Your button XAML would then look something like this :-
<Button cmd:ButtonBaseExtensions.Command="{Binding MyButtonClickAction}"/>
精彩评论