When you develop UI in WPF you need to bind your UI elements with the source objects.Specifically you bind the properties in the source object to the properties in the target object.For example you may be binding the text property of a textbox with a property called name in the source object called Employee.
For data binding the source and destination properties ,both properties should have same or compatible data types.Sometimes you may find a scenario where these properties have incompatible types.In such a scenario you can not bind the source and target properties.To bind the two properties together you need an interface or converter between these source and target properties.Some common scenario you may have encountered which prevented you from data binding the properties:
- You need to hide a UI element such as textbox based on a boolean value.
- You need to bind the checkbox with a non boolean property.
This converter is called value converter in WPF.
Example of Value Converter in WPF
To define a value converter you just need to implement the interface IValueConverter and use it while data binding.
There is a Employee class which we will be data binding to the UI
public class Person { public bool IsPermanent { get; set; } public string Name { get; set; } public string StaffId { get; set; } public Person() { IsPermanent = false; } }
For the sake of simplicity the Employee class contains three properties IsPermanent ,StaffId and Name.In this scenario you should have a check box element in the UI for the IsPermanent property.
<CheckBox IsChecked="{Binding IsPermanent}"></CheckBox>
Now you you want to display the StaffId only if the Employee is a permanent employee.For this you can implement the value converter as below:
public class BoolToVisibilityConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { //bool val = System.Convert.ToBoolean(value); return (bool)value ? Visibility.Visible : Visibility.Collapsed; } public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { throw new NotImplementedException(); //return (bool)value ? Visibility.Visible : Visibility.Collapsed; } }
In the UI you can add a text box for the StaffId as below
<TextBox Text="{Binding StaffId}" Visibility="{Binding IsPermanent,Converter={StaticResource boolToVisibilityConverter}}"></TextBox>
Now the text box for staff id will only be visible when the IsPermanent property is true.
Leave a Reply