Binding to Elements Outside of a DataTemplate in XAML
Problem
It is not always possible to access elements outside of a DataTemplate using the ElementName binding. This is a common scenario when you want to bind to a property of the parent DataContext from within the ItemTemplate of something like an ItemsControl.
Solution
The AncestorBinding markup extension in the Uno Toolkit provides a way to find the nearest ancestor of a specific type and bind to its properties.
Example Code
<uer:FeedView Source="{Binding TrendingNow}">
<muxc:ItemsRepeater ItemsSource="{Binding Data}">
<muxc:ItemsRepeater.ItemTemplate>
<DataTemplate>
<ToggleButton Style="{StaticResource IconToggleButtonStyle}"
IsChecked="{Binding IsFavorite}"
Command="{utu:AncestorBinding AncestorType=uer:FeedView, Path=DataContext.FavoriteRecipe}"
CommandParameter="{Binding}">
</ToggleButton>
</DataTemplate>
</muxc:ItemsRepeater.ItemTemplate>
</muxc:ItemsRepeater>
</uer:FeedView>
Source Code
- Home Page
- Create/Update Cookbook Page
- Recipe Details Page (ToggleButton Like Command)
- Recipe Details Page (ToggleButton Dislike Command)