2

I have a ListView on my Windows Universal page. I am using a UserControl to define my ItemTemplate so that I can use the RelativePanel and VisualStateManager to control how my items appear depending on the screen size...

<ListView ItemsSource="{Binding Path=AllThings}"
          ItemContainerStyle="{StaticResource ListViewItemStyle}">
    <ListView.ItemTemplate>
         <DataTemplate>
             <local:CrossingControl />
         </DataTemplate>
    </ListView.ItemTemplate>
</ListView>

I have a button in my UserControl where I want to bind its Command to a command property in the ViewModel that is the DataContext of the list itself...

<UserControl ...>
    <RelativePanel>
    <StackPanel x:Name="crossedEntryPanel">
        <Button Command="{Binding DataContext.DeleteCommand,
                          RelativeSource={RelativeSource Mode=TemplatedParent}}"
                                    CommandParameter="{Binding}"

I have tried using the ElementName binding, but it doesn't seem to work (I suppose because my listview element name is defined in another xaml file). I have also tried the above RelativeSource binding, but that doesn't seem to work either. How can I bind this properly?

Romasz
  • 29,662
  • 13
  • 79
  • 154
Simon Williams
  • 1,016
  • 3
  • 11
  • 27

1 Answers1

4

You can make use of Tag property to save the DataContext of ListView and use it in UserControl

Here how it is done

<ListView ItemsSource="{Binding Path=AllThings}" x:Name="listview"
                        ItemContainerStyle="{StaticResource ListViewItemStyle}">
            <ListView.ItemTemplate>
                <DataTemplate>
                    <local:CrossingControl  Tag="{Binding DataContext,ElementName=listview}" />
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>

<UserControl x:Name="usercontrol" ...>
    <RelativePanel>
    <StackPanel x:Name="crossedEntryPanel">
        <Button Command="{Binding Tag.DeleteCommand,ElementName=usercontrol}"
                                    CommandParameter="{Binding}"

RelativeSource={RelativeSource Mode=TemplatedParent}}":- this points to controltemplate of button

Archana
  • 3,213
  • 1
  • 15
  • 21