In this recipe let's understand the DataMode property of the Binding class. By default, the Data Mode property is OneWay. It has two other modes, OneTime and TwoWay. OneTime mode pulls the data only once from the source. OneWay mode only pulls the data from the source and updates it every time the source changes. TwoWay mode not only pulls the data from the source, but also pushes the changes back. These settings are not only used for data sources, they can also be tied to another element. Let's learn how we can use a TwoWay mode for the slider control to indicate the changes in a text block.
MainPage.xaml
page and add a text block and a slider control to the existing page after the Notes
text block. Here the slider control's value property is set to bind to text block control tbPriorityContent
.<TextBlock x:Name ="tbPriorityContent" Text ="{Binding Priority}" Grid.Row="3" Grid.Column ="1" />
<Slider x:Name ="slPriority" Width="300" Minimum="1" Maximum="10" Grid.Row="4" SmallChange="10" Grid.ColumnSpan ="2" Orientation="Horizontal" HorizontalAlignment="Left" Value="{Binding ElementName=tbPriorityContent, Path=Text, Mode=TwoWay}" />
DataClass.cs
file and add another property called Priority
to the DataClass
, as follows:public class DataClass { public string Name { get; set; } public string Notes { get; set; } public int Priority { get; set; } }
MainPage.xaml.cs
file and add another line in the object initializer to set the Priority
to 8
. This is illustrated in the following code:public MainPage()
{
InitializeComponent();
// Initialize our data class
myData = new DataClass()
{
Name = "Name 1",
Notes = "Note 1",
Priority = 8
};1
// Set the DataContext of the grid to DataClass
LayoutRoot.DataContext = myData;
tbPriorityContent
content. Also, try to move the slider position and you will see the text block value also changing.You noticed that when the slider changes its position the priority text block gets updated automatically. Because of the two-way mode setting the text block gets the data updated in the control's property as soon as it is changed. Similarly, when the text block is initialized with a value, the slider value is changed. This demonstrates how the controls can be refreshed with two-way mode.