Associating with the MVVM Light Relay Command Inside a Windows Phone 7 Control Data Template

I am trying to bind a button to a viewmodel command using MVVM Light commands, and for some reason the command does not seem to be called. Usually I don't have problems with commands, but this one seems to ignore the binding.

Here is 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 the list that is created after starting my application, and I wonder if this is a problem. My theory is that a view model is created and the constructor tries to establish a binding using the relay command, but since the list does not yet have elements, the binding does not complete correctly.

Linking with MyProperty and MyOtherProperty works fine.

Any suggestions on how I can get this to work?

+4
source share
2 answers

The problem is that inside the DataTemplate, the DataContext is the element itself, not your ViewModel. So when you say {Binding MyButtonActionClick} , the binding looks for a command called MyButtonActionClick for the element, which I assume is just a simple object and does not have its own properties.

There are several ways around this. Since you are already using MMVM Light, a better approach would be to define your collection as List<FooViewModel> rather than List<Foo> and transfer your items to your own ViewModel class. You can then add the MyButtonActionClick command to this ViewModel and return to the parent ViewModel.

Otherwise, change the binding of the command so that it looks at the DataContext of the ItemsControl element itself. Take a look at this question (and the accepted answer, of course) for some ideas on how to do this.

+7
source

As an additional note, you might want to use the ButtonBaseExtensions class when binding commands to your buttons. This class can be found in the GalaSoft.MvvmLight.Command namespace in the GalaSoft.MvvmLight.WP7 assembly.

Your XAML namespace will include: -

 xmlns:cmd="clr-namespace:GalaSoft.MvvmLight.Command;assembly=GalaSoft.MvvmLight.WP7" 

Your XAML button will look something like this: -

 <Button cmd:ButtonBaseExtensions.Command="{Binding MyButtonClickAction}"/> 
+7
source

Source: https://habr.com/ru/post/1339121/


All Articles