Click here to Skip to main content
15,886,095 members
Articles / Programming Languages / C# 4.0
Tip/Trick

Create a Formatted TextBox in Silverlight

Rate me:
Please Sign up or sign in to vote.
0.00/5 (No votes)
18 May 2011CPOL2 min read 12.4K   1   1
Hi Guys

I thought I'd share how to create a Formatted TextBox in Silverlight as I found little resources as to some small things I needed...

1. First of all I created a FormatTextBox which inherits from a base control which is TextBox...

public class FormatTextBox : TextBox


You can also add properties to bind to in your inherited class...

public Visibility VisibleInnerLeft
{
    get { return (Visibility)GetValue(VisibleInnerLeftProperty); }
    set { SetValue(VisibleInnerLeftProperty, value); }
}

public Visibility VisibleInnerRight
{
    get { return (Visibility)GetValue(VisibleInnerRightProperty); }
    set { SetValue(VisibleInnerRightProperty, value); }
}

public DependencyProperty VisibleInnerLeftProperty { get; set; }
public DependencyProperty VisibleInnerRightProperty { get; set; }

public FormatTextBox()
{
    VisibleInnerLeftProperty = DependencyProperty.Register("VisibleInnerLeft", typeof(Visibility), typeof(FormatTextBox), new PropertyMetadata(Visibility.Collapsed));
    VisibleInnerRightProperty = DependencyProperty.Register("VisibleInnerRight", typeof(Visibility), typeof(FormatTextBox), new PropertyMetadata(Visibility.Collapsed));
}


2. I then created a Template for this control in a ResourceDictionary. (I want this control to display differently than a normal TextBox so I'm defining it's style and template in the ResourceDictionary)

Note that if you'd want to get hold of a template of a control you can use Expression Blend to get it by right-clicking on the control in the "Objects and Timeline" window, go to "Edit Template", then select "Edit a Copy...".
If you view the XAML of your project or solution in Blend you will see it created the Template for the control in the control's resources tag (<UserControl.Resources>).
You can copy this and use in your ResourceDictionary... Something like this...

XML
<Style TargetType="local:FormatTextBox">
...
<Setter Property="Template">
    <Setter.Value>
        <ControlTemplate TargetType="local:FormatTextBox">
        ...
            <Grid>
                        <ContentControl x:Name="ContentInnerLeft" Visibility="{TemplateBinding VisibleInnerLeft}" Padding="{TemplateBinding Padding}" />
                        <ScrollViewer x:Name="ContentElement" Padding="{TemplateBinding Padding}"/>
                        <ContentControl x:Name="ContentInnerRight" Visibility="{TemplateBinding VisibleInnerRight}" HorizontalAlignment="Right" Padding="{TemplateBinding Padding}" />
                    </Grid>
        ...
        </ControlTemplate>
    </Setter.Value>
</Setter>
...
</Style>


Notice that when binding properties in a control's template you have to use TemplateBinding i.e. Visibility="{TemplateBinding VisibleInnerLeft}"

3. I then created the ValueConverter which should implement IValueConverter.

C#
using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Data;
public class FormatConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        string result = value.ToString();
        string valueStr = value.ToString();
        IConvertible iConv = valueStr;
        double valueTest = 0;
        if (Double.TryParse(valueStr, out valueTest))
        {
            double valueDbl = iConv.ToDouble(null);
            result = String.Format(culture, parameter.ToString(), valueDbl);
        }
        return result;
    }
    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        return true;
    }
}


I had to do some strange things in the converter. As locally the converter contains a Convert function thus you can't use something like Convert.ToDouble(dblValue). As you can see I created a new instance of the IConvertible interface. This allows you to use .ToDouble...

And then finally I use String.Format to format the converted double value to the format which was passed as the converter's parameter.

4. Using the FormatConverter you can either use it in XAML but in my case I had to use it in C#...

this.view.FormatTextBox.VisibleInnerRight = Visibility.Visible;
this.view.FormatTextBox.Text = "123.45";
            
Binding formatBinding = new Binding("Text");
formatBinding.Source = this.view.FormatTextBox;

FormatConverter formatConverter = new FormatConverter();
formatBinding.Converter = formatConverter;
formatBinding.ConverterParameter = "{0:c}";

CultureInfo formatCulture = new CultureInfo(CultureInfo.CurrentCulture.Name);
formatCulture.NumberFormat.NumberGroupSeparator = ",";
formatBinding.ConverterCulture = formatCulture;

BindingOperations.SetBinding(this.view.FormatTextBox, TextBox.TextProperty, formatBinding);


The converter parameter "{0:c}" gets passed to the Convert function in FormatConverter which is then passed to String.Format which will format the text as a currency using the regional settings of the computer it is running on (CultureInfo). Any other standard or valid parameters for String.Format can be used to format the text.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Unknown
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralCan use System.Convert instead of IConvertible... Pin
Ewert Bergh29-May-11 23:48
Ewert Bergh29-May-11 23:48 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.