Skip to main content

WPF MultiValue Converter

Introduction

In my previous article we have discussed what is converter and the type of converters in WPF. This article describes about the second converter that is MultiValue Converters with code example.

Getting Started

A Multivalue Converter is required when your target is bound to multiple sources and if the source and targets have different data formats or need some conversion. Assume you have three text box controls and one button control and you want to enable the button control when all the text of the text boxes are filled.

For this case we need to create a Multivalve Converter class that inherits the IMultiValueConverter interface of the System.Windows.Data namespace that will check all the text of the textboxes to determine whether it is filled or not, if it is filled then it will return true otherwise return false and that will enable or disable the button control.

 using System;   
 using System.Collections.Generic;   
 using System.Linq;   
 using System.Text;   
 using System.Threading.Tasks;   
 using System.Windows.Data;   
 namespace ValueConverters   
 {   
   public class MultivalueConverter:IMultiValueConverter   
   {   
     public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture)   
     {   
       if (values.Count() >= 2)   
       {   
         if (string.IsNullOrEmpty(values[0].ToString()) || string.IsNullOrEmpty(values[1].ToString()))   
           return false;   
         else return true;   
       }   
       else   
         return false;   
     }   
     public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture)   
     {   
       throw new NotImplementedException();   
     }   
   }   
 }   

In the preceding code, the convert function checks all the bound data, if any of them are null or empty then it will return false to disable the button control otherwise it will return true to enable the button control. In this example if the text of the two texboxs is found to be empty then the convert function will return false otherwise true.

I have another example for the convertback function. Let's say you have three textboxes, the first TextBox is for taking the first name of a person, the second is for taking the last name and the third one is for displaying the text of the preceding two textboxs jointly with a space between them and vice-versa. In this case the convert back function of IMultiValueConverter interface must be usde. In the following code example of the fullnameconverter class I have used both the convert and convertback functions to do it.

 using System;   
 using System.Collections.Generic;   
 using System.Linq;   
 using System.Text;   
 using System.Threading.Tasks;   
 using System.Windows.Data;   
 namespace ValueConverters   
 {   
   public class FullNameConverter : IMultiValueConverter   
   {   
     public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture)   
     {   
       if (values != null)   
       {   
         return values[0] + " " + values[1];   
       }   
       return " ";   
     }   
     public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture)   
     {   
       string[] values=null;   
       if (value != null)   
         return values = value.ToString().Split(' ');   
       return values;   
     }   
   }   
 }   

The convert function in the preceding code concatenates the two data items coming from the two sources with a space between them and returns the concatenated data to the target. The convert back function splits the concatenated string with a space to an array of strings and returns the items of the array to the corresponding source.

In the preceding scenario the convert back function takes the text of both the first name TextBox and the last name TextBox and concatenates the text with a space between the two texts and returns that to the third TextBox.

Again, when you fill in the data in the third TextBox, the convert back function takes the text and splits it into an array string using a space and returns that to the source textboxes (first name TextBox and last name TextBox).

Use of Converter

To use a converter you need to create the object of converter class in resource. After declaring the resource it is necessary to use it with binding. See the following XAML code example.

 <Window x:Class="ValueConverters.MultiValueConverter"   
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"   
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"   
     xmlns:local="clr-namespace:ValueConverters"   
     Title="MultiValueConverter" Height="300" Width="448.872">   
   <Window.Resources>   
     <local:MultivalueConverter x:Key="multivalueConverter"></local:MultivalueConverter>   
     <local:FullNameConverter x:Key="fullNameConverter"></local:FullNameConverter>   
   </Window.Resources>   
   <Grid>   
     <TextBlock Text="Value Converter Exampkle" HorizontalAlignment="Stretch" VerticalAlignment="Top" TextAlignment="Center"></TextBlock>   
     <TextBlock Text="First Name" HorizontalAlignment="Left" VerticalAlignment="Top" TextAlignment="Center" Margin="10,38,0,0"></TextBlock>   
     <TextBox Name="txtFirstName" HorizontalAlignment="Left" VerticalAlignment="Top" Height="25" Width="255" Margin="91,29,0,0" ></TextBox>   
     <TextBlock Text="Last Name" HorizontalAlignment="Left" VerticalAlignment="Top" TextAlignment="Center" Margin="11,68,0,0"></TextBlock>   
     <TextBox Name="txtLastName" HorizontalAlignment="Left" VerticalAlignment="Top" Height="25" Width="255" Margin="91,59,0,0" ></TextBox>   
     <TextBlock Text="Full Name" HorizontalAlignment="Left" VerticalAlignment="Top" TextAlignment="Center" Margin="14,105,0,0"></TextBlock>   
     <TextBox Name="txtFullName" HorizontalAlignment="Left" VerticalAlignment="Top" Height="25" Width="332" Margin="14,126,0,0" >   
       <TextBox.Text>   
         <MultiBinding Converter="{StaticResource fullNameConverter}">   
           <Binding ElementName="txtFirstName" Path="Text" Mode="TwoWay" UpdateSourceTrigger="PropertyChanged"></Binding>   
           <Binding ElementName="txtLastName" Path="Text" Mode="TwoWay" UpdateSourceTrigger="PropertyChanged"></Binding>   
         </MultiBinding>   
       </TextBox.Text>   
     </TextBox>   
     <Button Content="Click" HorizontalAlignment="Left" VerticalAlignment="Top" Height="23" Width="50" Margin="165,171,0,0">   
       <Button.IsEnabled>   
         <MultiBinding Converter="{StaticResource multivalueConverter}">   
           <Binding ElementName="txtFirstName" Path="Text"></Binding>   
           <Binding ElementName="txtLastName" Path="Text"></Binding>   
         </MultiBinding>   
       </Button.IsEnabled>   
     </Button>   
   </Grid>   
 </Window>   

Related Articles

  1. WPF Converters
  2. WPF Value Converters
  3. WPF Binding

Summary

In this article we have discussed about MultiValue Converter, hope this article may helpful to you.

Thanks

Comments

Popular posts from this blog

Generate QR Code in WPF

Introduction In my previous two blogs, we have discussed how to display generate and display various barcodes on the web page. In this blog, we are going to demonstrate how to Generate QR Code in the WPF application. Getting Started Here in the demonstration Generate QR Code in WPF , will generate QR code using third party library as there is not inbuilt library provided by Microsoft to generate QR code and will display in WPF image control, In the below, we will see the steps to display QR Code. As I mentioned in the above paragraph that there is no inbuild library provided by Microsoft to generate QR code, I have taken the help of the ZXing library which is a third party free library and available Nuget. This library provides various options to generate barcodes and QR Code from the user-friendly text. Generate QR Code in WPF Here are the steps to generate QR code and let's follow the steps to complete demonstrations. Demonstration:- Generate QR Code Open visual stud

Creating Application in Prism

Introduction This article explains an illustration of creating a windows application in Prism Library(WPF Prism). The solution includes recommended practices and techniques and is the basis for the procedures in Prism. This illustration created in the Visual Studio 2012, It can also developed in the visual studio 2008 and 2010, because wpf supports from .net framework 3.5 to latest version. Microsoft.Practices.Prism.dll. This assembly contains the implementation of the Prism Library core components such as modularity, logging services, communication services, and definitions for several core interfaces. It also contains the implementation of Prism Library components that target WPF applications, including commands, regions, and events. Microsoft.Practices.Prism.UnityExtensions.dll. This assembly contains base and utility classes you can reuse in applications built with the Prism Library that consume the Unity Application Block. For example, it contains a bootstrapper base class

WPF Binding

Introduction This blog describes WPF Binding and the measure elements exist with binding with XAML example in XAML and code-behind. Getting Started Binding helps in WPF to flow data from one object to another object, the object which fetches data is called source and the object which receives the data is called target. The Object a be a UI control or object of a class that means in binding you can bind a property of a class and property of another control to WPF UI controls as well. XAML Example <TextBox x:Name="sourceText" Grid.Row="0" /> <Button Grid.Row="1" Content="{Binding ElementName=sourceText, Path=Text}"/> Code Example Button btn=new Button(); Binding binding = new Binding("Text"); binding.Source = sourceText; btn.SetBinding(Button.ContentProperty, binding); In WPF binding has some measure properties or elements that we are using while developing application or projects, here we are going to d