Search code examples
xamlwindows-store-apps

ListViewItem access property on viewmodel


I have a list of users on my viewmodel that I pass to the following listView:

                  <ListView
                  Background="Azure"
                  x:Name="ContactList"                  
                  ItemsSource="{Binding Path=User}"                 
                  SelectedItem="{Binding SelectedUser, Mode=TwoWay}">
                        <ListView.ItemTemplate>
                            <DataTemplate>
                                <Border Width="300" Height="Auto" BorderThickness="1">
                                    <StackPanel>
                                        <TextBlock>
                                    <Run Text="{Binding Name}" />                            
                                    <Run Text="{Binding Age}" />
                                        </TextBlock>
                                        <CheckBox Visibility="{???}">
                                            <TextBlock FlowDirection="LeftToRight"></TextBlock>
                                        </CheckBox>
                                    </StackPanel>
                                </Border>                              
                            </DataTemplate>
                        </ListView.ItemTemplate>
                    </ListView>

As you can see my DataTemplate contains a checkbox. I would like its Visibility to depend on a bool-property I have on my ViewModel. How can I access this property from within the listView?

From looking around here it seems like there are ways to access the ListView-items parent. I think that would do it for me. Can someone point me in the right direction . Thanks


Solution

  • The best way to do this is to include the visibility setting along with your user data. Assuming your view model visibility property is named CheckBoxVisibility, you would have something like this:

    <ListView ItemsSource="{Binding}" ...>
        <ListView.ItemTemplate>
            <DataTemplate>
                ...
                    <Run Text="{Binding Path=User.Name}" />
                    <Run Text="{Binding Path=User.Age}" />
                ...
                <CheckBox Visibility="{Binding Path=CheckBoxVisibility}">
                ...
            </DataTemplate>
        </ListView.ItemTemplate>
    </ListView>
    

    In WPF, you can use a RelativeSource=RelativeAncestor binding; however, this is not available in Window Store/Windows Phone 8+ apps.