View To View Binding In Xamarin.Forms

Here, we are learning a new concept called X:Reference markup extension and its usage in View to View binding.
 
Generally, we bind the data between a View and a ViewModel for reflecting the changes if any one of the areas like View or ViewModel occurs. But when we design pages, we have some situation like we need to link the data between two Views, because if any data changes in one View, it will automatically reflect in another View. Here is the sample example of View-to-View Binding.
 
Sample code
  1. <ContentPage xmlns="http://xamarin.com/schemas/2014/forms"  
  2. xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"  
  3. xmlns:local="clr-namespace:ReferenceSampleInXamarinForms"  
  4. x:Class="ReferenceSampleInXamarinForms.MainPage">  
  5. <StackLayout>  
  6.    <Slider x:Name="slider1" Maximum="360" VerticalOptions="CenterAndExpand"></Slider>  
  7.       <Label x:Name="label1" BindingContext="{x:Reference Name=slider1}" Text="{Binding Path=Value}"  
  8.       FontAttributes="Bold" FontSize="Large" HorizontalOptions="Center" VerticalOptions="CenterAndExpand"> </Label>  
  9.       <Label x:Name = "lable2" BindingContext="{x:Reference Name=label1}" Text="   {Binding Path=Text}" HorizontalOptions="Center" VerticalOptions="CenterAndExpand"></Label>  
  10.    </StackLayout>  
  11. </ContentPage>   
In the above sample code, we have one slider control and two text labels. Here, we set the maximum value of slider as '360'. Apart from slider, we have taken two text labels - one label displays the slider value and the oher one displays the lable1 value, where 'X:Reference' markup extension is used if you want to bind the data from one View to another View in same page.
 
In the above code, 'label1' text value is bound with the slider value. So, we write the binding context property in label1 control with x:reference markup extension. While in the 'Name' property, we are writing slider x:name value for getting the reference from the slider. For displaying the slider value in lable1, we are binding the text to the property like 'path'. Here, path value is assigned with slider value for displaying the slider value in label1.
 
In the above code, we have one more View to View binding between label1 and lable2 where label2 value text is bound with lable1 text values, i.e., Text="{Binding Path=Text}. So when we run the above code and if we move the slider, that slider value displays in the label1 and lable1 value is displayed in label2.