This is another in my post series on WinRT programming for C# developers. For review, I’m blogging my notes on running and modifying each of the samples from this page: http://code.msdn.microsoft.com/windowsapps/Windows-8-Modern-Style-App-Samples
The next sample provides an overview of WinRT data binding. This sample actually has seven different scenarios; it’s one of the biggest samples so far.
However, I’m only going to briefly cover this sample. TLDR Version: If you’ve used DataBinding in WPF or Silverlight, it is very familiar.
For those interested in more:
You can support one way, two way, and one time bindings:
<TextBox x:Name="tbOneWayDataBound"
Text="{Binding ElementName=sliderOneWayDataSource, Path=Value, Mode=OneWay}"
Grid.Column="2" Grid.Row="2" HorizontalAlignment="Left" VerticalAlignment="Top" Width="150"/>
<TextBox x:Name="tbTwoWayDataBound"
Text="{Binding ElementName=sliderTwoWayDataSource, Path=Value, Mode=TwoWay}"
Grid.Column="2" Grid.Row="4" HorizontalAlignment="Left" VerticalAlignment="Top" Width="150"/>
<TextBox x:Name="tbOneTimeDataBound"
Text="{Binding ElementName=sliderOneTimeDataSource, Path=Value, Mode=OneTime}"
Grid.Column="2" Grid.Row="6" HorizontalAlignment="Left" VerticalAlignment="Top" Width="150"/>
You can create Converters similar to WPF or Silverlight:
<TextBox x:Name="tbValueConverterDataBound"
Text="{Binding ElementName=sliderValueConverter, Path=Value, Mode=OneWay, Converter={StaticResource GradeConverter}}"
Margin="5" Width="150"/>
public class S2Formatter : IValueConverter
{
//Convert the slider value into Grades
public object Convert(object value, System.Type type, object parameter, string language)
{
int _value;
string _grade = string.Empty;
//try parsing the value to int
if (Int32.TryParse(value.ToString(), out _value))
{
if (_value < 50)
_grade = "F";
else if (_value < 60)
_grade = "D";
else if (_value < 70)
_grade = "C";
else if (_value < 80)
_grade = "B";
else if (_value < 90)
_grade = "A";
else if (_value < 100)
_grade = "A+";
else if (_value == 100)
_grade = "SUPER STAR!";
}
return _grade;
}
public object ConvertBack(object value, System.Type type, object parameter, string language)
{
throw new NotImplementedException(); //doing one-way binding so this is not required.
}
}
Other scenarios in this sample show how to respond to data source changes (It looks like INotifyPropertyChanged), bind to elements in a collection (just like in WPF or Silverlight) , bind to color properties (just like WPF and Silverlight), modify collections (like WPF and Silverlight), and navigate collections (like in WPF or Silverlight).
In short, it’s really familiar code, if you’ve done anything with WPF or Silverlight.
