XAML Value Converter With A Simple Example

In this article, I'm going to show you how you can use a value converter in XAML to convert one format of data into another format. In our case, we'll convert a string value (value in textbox) to a Boolean value (checked status of a checkbox).

Things we are going to discuss

  • What are value converters?
  • Why do we need them?
  • How to perform value conversion?
  • Perform value conversion using built-in .NET Classes.
  • Getting Started with a Simple Example.

Let's discuss each one by one.

What are Value Converters?

Value Converters are the classes that are used to convert one form of data into another.

Why do we need them?

There are certain case studies when we need to convert the data from one format to another format in software development, especially in application development.

So, we perform the conversion like

  • Color to string
  • Bool to string
  • String to color etc.

How to perform value conversion?

We can write our custom code to convert the data from one form to another but it will be time-consuming and will increase the complexity. So, we'll use built-in .NET classes.

Let's get started with a simple example.

Suppose we have a control as a textbox and another control as a Checkbox. We want to check the checkbox whenever the user writes "Checked" into the textbox. Like this.

XAML

And when a user writes something else, this checkbox will be unchecked like this.

XAML

In this process, indirectly, we are converting a string value to a relevant Boolean value. As this is not possible directly, we'll use the IValueConverter Interface and implement that in a user-defined class. That class will be used as a local resource in XAML code. To learn about a local resource, you can go through this article. Our control-binding property will consume this local resource.

Create a new UWP Empty Project

XAML

Now, add a new class with the name "" to the project.

XAML

Now, click the class option and write the name of the class.

XAML

This is the class you just added.

public class StringToBoolConverter { 
}

Now, inherit this class with IValueConverter.

Note. You need to use Windows. UI.Xaml.Data namespace to use that interface.

using Windows.UI.Xaml.Data;  

Now, inherit the class with the interface.

XAML

Press [ctrl +. ] on the Interface name and you'll see the options on the left side of the class. Select the first one, i.e., "Implement Interface". Two functions will be added to the class with the names.

  • Convert()
  • ConvertBack()

See the updated class now.

public class StringToBoolConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, string language)
    {
        throw new NotImplementedException();
    }
    public object ConvertBack(object value, Type targetType, object parameter, string language)
    {
        throw new NotImplementedException();
    }
}

Now, we have to write the definition of these two methods. But before that, we must understand what we are going to do in both methods.

Convert()Convert() method takes data from Control; in our case, it will take string data from the textbox. And, we'll write custom code to convert that string into Bool value. See the method definition.

public object Convert(object value, Type targetType, object parameter, string language)
{
    bool CheckBoxStatus = false;
    if (!string.IsNullOrEmpty(value.ToString()))
    {
        if (value.ToString().ToUpper() == "CHECKED")
        {
            CheckBoxStatus = true;
        }
        else
        {
            CheckBoxStatus = false;
        }
    }
    return CheckBoxStatus;
}

Building necessary UI

Now, we are going to place controls using the XAML code. Open MainPage.xaml from Solution Explorer.

XAML

You'll get a blank grid like this.

XAML

Place a textbox and a checkbox into the Grid. Use the following XAML code for this.

<StackPanel Orientation="Vertical" HorizontalAlignment="Center" VerticalAlignment="Center">
    <TextBox VerticalAlignment="Center" Width="150" PlaceholderText="Enter your text"></TextBox>
    <CheckBox HorizontalAlignment="Center"></CheckBox>
</StackPanel>

After adding up the UI, we are supposed to add local resources. In this project, the local resource is a converter class that we added recently to our project. Now, we are supposed to provide a reference for that class to the XAML Code. So, add the following resource before the opening of Grid Tag in MainPage.xaml, as shown in the below picture.

XAML

Here is the code.

<Page.Resources>
    <local:StringToBoolConverter x:Key="StringToBoolConverterKey"></local:StringToBoolConverter>
</Page.Resources>

Don't forget to build your project, otherwise you'll see an exception in designers like this.

XAML

Our project setup and resources are ready. The next step is to bind the IsChecked property of the Checkbox with the string of the textbox. We've already written code for that. Now, we just have to mention that the code is binding in the following way.

XAML

Here is the code for you to copy from.

<CheckBox HorizontalAlignment="Center"
          IsChecked="{Binding Path=Text,
                              ElementName=txtBox,
                              Converter={StaticResource StringToBoolConverterKey}}">
</CheckBox>

Now, run the project and type some words in the textbox.

XAML

In my case, it is working fine. If you have any problems, please notify me via the Comments section.


Recommended Free Ebook
Similar Articles