0

I am using mvvm light in a WP7 app. I have a listbox with an itemsource of a collection of objects. The ItemTemplate DataTemplate for the listbox contains a button. The button contains a textblock that displayes a property from the bound object. How do I assign the Command to the button without changing the datacontext the textblock or the CommandParameter that gets the item bound to the itemtemplate?

<ListBox x:Name="listBox" ItemsSource="{Binding Main.SomeCollection}" >
     <ListBox.ItemTemplate>
          <DataTemplate>
            <Button 
                Command:ButtonBaseExtensions.Command="{Binding Main.MyCommand}"
                Cmmand:ButtonBaseExtensions.CommandParameter="{Binding}" />
                     <TextBlock Text="{Binding Title}"/>
            </Button>
          </DataTemplate>
      </ListBox.ItemTemplate>
</ListBox>

Thanks

Roger
  • 2,063
  • 4
  • 32
  • 65

1 Answers1

3

You need to get a reference to the DataContext on which the Command is located. In MVVM Light, we typically do this through the ViewModelLocator. Since the ViewModelLocator is exposed as a global resource (in App.xaml), you can do:

Command="{Binding Main.MyCommand, Source={StaticResource Locator}}"

Of course you can also do that visually in Blend.

Cheers, Laurent

LBugnion
  • 6,672
  • 2
  • 24
  • 28
  • Yes, that fixed the binding. How in Blend? #1, it's in a datatemplate, #2 I have not seen command props in Blend. – Roger Mar 31 '11 at 22:11
  • Yes sorry, I should have been more precise. In Windows Phone 7, the attached properties from ButtonBaseExtensions are not blendable unfortunately. Using the Blend binding editor is possible for WPF, Silverlight 4 (two versions of the framework that know the Command property natively). In Windows Phone 7, if you want blendability, you can use the EventToCommand component (from the MVVM Light Extras DLL) to attach to the Click event of the Button, and then you have full blendability. Cheers! – LBugnion Apr 01 '11 at 09:36
  • @LBugnion Sorry for rising old topic. The thing is that if i'm using the name of viewmodel (and viewmodel is not singletone: i'm passing parameters to constructor in locator), it is calling viewmodel's constructor for every item in the list, which has that command. Any workarounds? Actually, its quite obvious behavior, but just in case.. – Vitalii Vasylenko Apr 29 '13 at 19:20