Monday, December 31, 2012

WP7 XAML Bind to property in parent

WP7 XAML Bind to property in parent

I'm writting an app in WP7 (Silverlight 3). I have a view model that looks like this

public class MainViewModel {    public List<ActivityTypes> ActivityTypes{get;set;}    public RelayCommand LoadActivity{get;set;} } 

My pages datacontext is set to the view model and I have a listbox with it's item source set to the ActivityTypes collection. In the listbox I'm trying to render a list of buttons who's command is bound to the LoadActivity property on the viewmodel. RelayCommand is part of the MVVM Light toolkit in case you are wondering what it is.

The problem I am having is I can't find a way to bind my button command to the LoadActivity property as my listbox has it's itemsource set to the Activitytypes collection and this property is in the parent. I've read about FindAncester but it doesn't look like this is supported in Silverlight 3.

My XAML looks like this

    <UserControl.Resources>         <DataTemplate x:Key="ActivityTypeListTemplate">             <StackPanel>                 <Button Command="{Binding LoadActivity}"> <!--binding not found as we're in the collection-->                     <TextBlock Text="{Binding Name}" FontSize="50"/>                 </Button>             </StackPanel>         </DataTemplate>     </UserControl.Resources>      <Grid x:Name="LayoutRoot" Background="{StaticResource PhoneChromeBrush}">         <ListBox Margin="0" ItemsSource="{Binding ActivityTypes}" ItemTemplate="{StaticResource ActivityTypeListTemplate}"/>     </Grid> 

What's the best way to code something like this?

Answers & Comments...

Answer: 1

There is no "direct" way to do this. You can set the Buttons DataContext to your MainViewModel (preferably as a StaticResource link) and the it would work.

Take a look at Bind to parent object in xaml

by : Igor Kulmanhttp://stackoverflow.com/users/581164




No comments:

Post a Comment

Send us your comment related to the topic mentioned on the blog