RadControls for Silverlight

The purpose of this tutorial is to show you how to use RadMaskedTextBox in data binding scenarios. The final result should look like the one on the snapshot below:

A RadComboBox is populated with Employee business objects. Several RadMaskedTextBox controls are used for editing the currently selected employee. The Value property of each RadMaskedTextBox is data bound to the corresponding property of the business object. Also note that the Culture property of the last two RadMaskedTextBox controls are data bound to a Culture property of the business object.

In the beginning, you need to create a new class named Employee.

CopyC#
public class Employee
{
    private string name;
    private string phone;
    private DateTime hireDate;
    private decimal salary;
    private string culture;
    public Employee( string name, string phone, DateTime hireDate, decimal salary, string culture )
    {
        this.Name = name;
        this.Phone = phone;
        this.HireDate = hireDate;
        this.Salary = salary;
        this.Culture = culture;
    }
    public string Name
    {
        get
        {
            return name;
        }
        set
        {
            name = value;
        }
    }
    public string Phone
    {
        get
        {
            return phone;
        }
        set
        {
            if ( String.IsNullOrEmpty( value ) ||
                value.Length < 9 )
                throw new Exception( "Please enter a nine digits phone number." );
            phone = value;
        }
    }
    public DateTime HireDate
    {
        get
        {
            return hireDate;
        }
        set
        {
            hireDate = value;
        }
    }
    public decimal Salary
    {
        get
        {
            return salary;
        }
        set
        {
            salary = value;
        }
    }
    public string Culture
    {
        get
        {
            return culture;
        }
        set
        {
            culture = value;
        }
    }
}
CopyVB.NET
Public Class Employee
 Private m_name As String
 Private m_phone As String
 Private m_hireDate As DateTime
 Private m_salary As Decimal
 Private m_culture As String
 Public Sub New(name As String, phone As String, hireDate As DateTime, salary As Decimal, culture As String)
  Me.Name = name
  Me.Phone = phone
  Me.HireDate = hireDate
  Me.Salary = salary
  Me.Culture = culture
 End Sub
 Public Property Name() As String
  Get
   Return m_name
  End Get
  Set
   m_name = value
  End Set
 End Property
 Public Property Phone() As String
  Get
   Return m_phone
  End Get
  Set
   If [String].IsNullOrEmpty(value) OrElse value.Length < 9 Then
    Throw New Exception("Please enter a nine digits phone number.")
   End If
   m_phone = value
  End Set
 End Property
 Public Property HireDate() As DateTime
  Get
   Return m_hireDate
  End Get
  Set
   m_hireDate = value
  End Set
 End Property
 Public Property Salary() As Decimal
  Get
   Return m_salary
  End Get
  Set
   m_salary = value
  End Set
 End Property
 Public Property Culture() As String
  Get
   Return m_culture
  End Get
  Set
   m_culture = value
  End Set
 End Property
End Class

Note, that there is a validation of the Phone property - the user is required to enter nine digits phone number. RadMaskedTextBox provides out-of-the-box support for Silverlight Data Validation. Data validation, being one of the major points when building line-of-business applications, can help you to easily separate the validation logic from the application's UI. Thus, when the user enters improper value in the "Phone" MaskedTextBox, the control goes in invalid state.

Tip
For more information about data validation and RadMaskedTextBox, read here.

Create a new class named MyViewModel. It will expose an ObservableCollection of Employee objects and will initialize it.

CopyC#
public class MyViewModel
{
    public MyViewModel()
    {
        this.Data = new ObservableCollection<Employee>();
        this.Data.Add( new Employee( "Ivan", "111-111-111", DateTime.Now.AddDays( 1 ), 1000, "bg-BG" ) );
        this.Data.Add( new Employee( "Rudolf", "222-222-222", DateTime.Now.AddDays( 2 ), 2000, "de-DE" ) );
        this.Data.Add( new Employee( "Jaque", "333-333-333", DateTime.Now.AddDays( 3 ), 3000, "fr-FR" ) );
        this.Data.Add( new Employee( "Trijntje", "444-444-444", DateTime.Now.AddDays( 4 ), 4000, "nl-NL" ) );
        this.Data.Add( new Employee( "Nikolay", "555-555-555", DateTime.Now.AddDays( 5 ), 5000, "ru-RU" ) );
    }
    public ObservableCollection<Employee> Data
    {
        get;
        set;
    }
}
CopyVB.NET
Public Class MyViewModel
 Public Sub New()
  Me.Data = New ObservableCollection(Of Employee)()
  Me.Data.Add(New Employee("Ivan", "111-111-111", DateTime.Now.AddDays(1), 1000, "bg-BG"))
  Me.Data.Add(New Employee("Rudolf", "222-222-222", DateTime.Now.AddDays(2), 2000, "de-DE"))
  Me.Data.Add(New Employee("Jaque", "333-333-333", DateTime.Now.AddDays(3), 3000, "fr-FR"))
  Me.Data.Add(New Employee("Trijntje", "444-444-444", DateTime.Now.AddDays(4), 4000, "nl-NL"))
  Me.Data.Add(New Employee("Nikolay", "555-555-555", DateTime.Now.AddDays(5), 5000, "ru-RU"))
 End Sub
 Public Property Data() As ObservableCollection(Of Employee)
  Get
   Return m_Data
  End Get
  Set
   m_Data = Value
  End Set
 End Property
 Private m_Data As ObservableCollection(Of Employee)
End Class

The UI declaration can be seen in the next code-snippet:

CopyXAML
<UserControl xmlns:example="clr-namespace:Silverlight.Help.RadMaskedTextBox" xmlns:telerik="http://schemas.telerik.com/2008/xaml/presentation">
    <UserControl.Resources>
        <example:StringToCultureConverter x:Name="StringToCultureConverter" />
    </UserControl.Resources>
    <Grid x:Name="LayoutRoot" Background="White">
        <StackPanel>
            <TextBlock Text="Employees" />
            <telerik:RadComboBox x:Name="radComboBox" 
                                 Margin="0,5,0,10"
                                 ItemsSource="{Binding Path=Data}">
                <telerik:RadComboBox.ItemTemplate>
                    <DataTemplate>
                        <StackPanel Orientation="Horizontal">
                            <TextBlock Text="{Binding Path=Name}" />
                            <TextBlock Text=", Hired on: " />
                            <TextBlock Text="{Binding Path=HireDate, StringFormat=d}" />
                        </StackPanel>
                    </DataTemplate>
                </telerik:RadComboBox.ItemTemplate>
            </telerik:RadComboBox>
            <TextBlock Text="Name" />
            <telerik:RadMaskedTextBox Margin="0,5,0,10" 
                                      MaskType="None"
                                      Value="{Binding ElementName=radComboBox, Path=SelectedItem.Name, Mode=TwoWay}" />
            <TextBlock Text="Phone" />
            <telerik:RadMaskedTextBox Margin="0,5,0,10" 
                                      Mask="###-###-###"
                                      MaskType="Standard"
                                      Value="{Binding ElementName=radComboBox, Path=SelectedItem.Phone, Mode=TwoWay, ValidatesOnExceptions=True, NotifyOnValidationError=True}" />
            <TextBlock Text="Hire Date" />
            <telerik:RadMaskedTextBox Margin="0,5,0,10" 
                                      Culture="{Binding ElementName=radComboBox, Path=SelectedItem.Culture, Converter={StaticResource StringToCultureConverter}}"
                                      Mask="d"
                                      MaskType="DateTime"
                                      Value="{Binding ElementName=radComboBox, Path=SelectedItem.HireDate, Mode=TwoWay}" />
            <TextBlock Text="Salary" />
            <telerik:RadMaskedTextBox Margin="0,5,0,10" 
                                      Culture="{Binding ElementName=radComboBox, Path=SelectedItem.Culture, Converter={StaticResource StringToCultureConverter}}"
                                      Mask="c3"
                                      MaskType="Numeric"
                                      Value="{Binding ElementName=radComboBox, Path=SelectedItem.Salary, Mode=TwoWay}" />
        </StackPanel>
    </Grid>
</UserControl>

The RadMaskedTextBox controls are data bound to the RadComboBox's SelectedItem via ElementBinding. Finally, in order to bind the Culture property, you have to declare an additional StringToCultureConverter. This is needed because the RadMaskedTextBox's Culture property is of type CultureInfo, while the Employee's Culture property is of type String.

CopyC#
public class StringToCultureConverter : IValueConverter
{
    public object Convert( object value, Type targetType, object parameter, System.Globalization.CultureInfo culture )
    {
        return new System.Globalization.CultureInfo( value.ToString() );
    }
    public object ConvertBack( object value, Type targetType, object parameter, System.Globalization.CultureInfo culture )
    {
        throw new NotImplementedException();
    }
}
CopyVB.NET
Public Class StringToCultureConverter
 Implements IValueConverter
 Public Function Convert(value As Object, targetType As Type, parameter As Object, culture As System.Globalization.CultureInfo) As Object
  Return New System.Globalization.CultureInfo(value.ToString())
 End Function
 Public Function ConvertBack(value As Object, targetType As Type, parameter As Object, culture As System.Globalization.CultureInfo) As Object
  Throw New NotImplementedException()
 End Function
End Class

Finally, set the MyViewModel instance as the DataContext of the UserControl.

CopyC#
this.DataContext = new MyViewModel();
CopyVB.NET
Me.DataContext = New MyViewModel()

See Also