开发者

How to set ButtonBaseExtensions.Command DataContext, and not change the buttons' context

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 textbl开发者_高级运维ock 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


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜