Search code examples
c#xamlwindows-store-apps

windows store app, bind to parent gridview property


How to bind parent property from itemTemplate gridview ?

<GridView ItemsSource="{Binding UsersViewModel}" ItemTemplate="{StaticResource UsersTemplate}">            

<DataTemplate x:Key="UsersTemplate">        
        <ListView VerticalAlignment="Top" ItemsSource="{Binding Users}"
                  Height="{Binding Window.Current.Bounds.Height}"   
                  Width="{Binding PARENT?.ColWidth}"
                  ScrollViewer.VerticalScrollBarVisibility="Visible"                    
                  ItemTemplateSelector="{StaticResource UserTemplateSelector}"
                  ItemContainerStyle="{StaticResource LvItemStyle}" >
        </ListView>        
</DataTemplate>

ColWidth property is defined in UsersViewModel


Solution

  • Something about your Xaml code doesn't feel right, since you are binding your GridView's ItemSource to that UsersViewModel that feels like a property instead of a Collection ! (ItemSource should be bound to a collection). If UsersViewModel is indeed a Collection of a class objects that has in it the ColWidth property, then a simple binding inside the DataTemplate should do the trick,

    Width="{Binding ColWidth}"
    

    Now if UsersViewModel is meant to be the GridView's DataContext, then you code probably should look something like that,

    <GridView DataContext="{Binding UsersViewModel}" ItemsSource="{Binding ACollectionInsideUsersViewModel}" ItemTemplate="{StaticResource UsersTemplate}">
    

    In this case if the ColWidth property is defined inside the UsersViewModel object, then the easiest way to access the parent DataContext from a child is by using ElementName Binding :

     <GridView DataContext="{Binding UsersViewModel}" ItemsSource="{Binding ACollectionInsideUsersViewModel}" Name="gridView">
            <GridView.ItemTemplate>
                <DataTemplate >
                    <ListView VerticalAlignment="Top" ItemsSource="{Binding Users}"
                  Height="{Binding Window.Current.Bounds.Height}"   
                  Width="{Binding DataContext.ColWidth,ElementName=gridView}"
                  ScrollViewer.VerticalScrollBarVisibility="Visible"                    
                  ItemTemplateSelector="{StaticResource UserTemplateSelector}"
                  ItemContainerStyle="{StaticResource LvItemStyle}" >
                    </ListView>
                </DataTemplate>
            </GridView.ItemTemplate>
        </GridView>