0

I have the following simple datatemplate within a flipview.

<FlipView x:Name="MyFlipview" ItemsSource="{x:Bind Path=ViewModel.Fleas}" >
       <FlipView.ItemTemplate>
            <DataTemplate  x:DataType="types:FleaType">     
               <TextBox x:Name ="Header" Text= "{Binding Path = ViewModel.GeneralComment}"></TextBox> 
               <TextBox x:Name ="FleaName" Text= "{Binding Path = FleaName}"></TextBox>

            </DataTemplate>
       </FlipView.ItemTemplate>
</FlipView>

But I dont know how to bind the Header textbox to generalcomment on the viewmodel as Generalcomment isnt part of the fleas collection. If anyone knows how to accomplish this it'd be much appreciated.

Thanks

GeorgeT
  • 97
  • 6

1 Answers1

1

You're looking for RelativeSource:

<FlipView x:Name="MyFlipview" ItemsSource="{x:Bind Path=ViewModel.Fleas}" >
       <FlipView.ItemTemplate>
            <DataTemplate  x:DataType="types:FleaType">     
               <TextBox x:Name ="Header" Text= "{Binding RelativeSource={RelativeSource AncestorType=UserControl}, Path=DataContext.GeneralComment}"></TextBox> 
               <TextBox x:Name ="FleaName" Text= "{Binding Path = FleaName}"></TextBox>

            </DataTemplate>
       </FlipView.ItemTemplate>
</FlipView>

There's more info here: RelativeSource on MSDN, essentially what this is doing is saying "Find the UserControl element above me, and bind to its DataContext which will be the view model, and then the GeneralComment property"; obviously if you're using something other than UserControl (e.g. a Page etc) then replace it with that type.


The One Where UWP Decides It Wants To Be Different.

As GeorgeT has indicated, AncestorType isn't supported in UWP, as such there's a way around this as explained here: How to do relativesource mode find ancestor (or equivalent) in UWP

The way I'd probably do it is to just set a name for the user control, and then do:

{Binding ElementName=MyUserControl, Path=DataContext.GeneralComment}
Community
  • 1
  • 1
Clint
  • 6,133
  • 2
  • 27
  • 48
  • Thanks, but this doesn't seem to work, I think that's because ancestortype is not supported in UWP. – GeorgeT Jun 15 '17 at 23:13
  • @GeorgeT Oh, well, isn't that an utter nightmare. *sigh* I've found something else that might help, I'll update my answer. – Clint Jun 15 '17 at 23:15
  • 1
    I was just looking at that post actually, but you saved me the bother of applying it to this issue. Thanks again, its all working now. – GeorgeT Jun 15 '17 at 23:31