Intersoft ClientUI 8 > ClientUI Fundamentals > Data Binding Overview > Data Binding How-to Topics > How-to: Convert Bound Data |
The following example shows how to convert bound data.
You can convert bound data by creating a class that inherits from IValueConverter.
The following example shows how to create a ColorConverter that can display the color of a rectangle in its RGBA string representation and convert it back to RGBA value when the string is changed.
C# |
Copy Code
|
---|---|
using System; using System.Windows.Data; using System.Windows.Media; namespace ClientUI.Samples.Converters { public class ColorConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { SolidColorBrush colorBrush = (SolidColorBrush)value; string A = BitConverter.ToString(new byte[] { colorBrush.Color.A }); string R = BitConverter.ToString(new byte[] { colorBrush.Color.R }); string G = BitConverter.ToString(new byte[] { colorBrush.Color.G }); string B = BitConverter.ToString(new byte[] { colorBrush.Color.B }); return "#" + A + R + G + B; } public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { string colorString = value as string; if (colorString.Length != 9) { throw new Exception("Invalid format"); } else { byte A = System.Convert.ToByte(colorString.Substring(1, 2), 16); byte R = System.Convert.ToByte(colorString.Substring(3, 2), 16); byte G = System.Convert.ToByte(colorString.Substring(5, 2), 16); byte B = System.Convert.ToByte(colorString.Substring(7, 2), 16); SolidColorBrush colorBrush = new SolidColorBrush(Color.FromArgb(A, R, G, B)); return colorBrush; } } } } |
XAML |
Copy Code
|
---|---|
<UserControl xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:Intersoft="http://intersoft.clientui.com/schemas" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:local="clr-namespace:ClientUI.Samples.Converters" mc:Ignorable="d" x:Class="ClientUI.Samples.MainPage" Width="800" Height="600"> <UserControl.Resources> <local:ColorConverter x:Key="ColorConverter"></local:ColorConverter> </UserControl.Resources> <Grid x:Name="LayoutRoot" Background="White"> <StackPanel d:LayoutOverrides="Width" HorizontalAlignment="Center" VerticalAlignment="Center"> <Rectangle x:Name="Rectangle1" Fill="#FFF3B509" Height="24" Stroke="Black" Width="100"/> <TextBox x:Name="TextBox1" TextWrapping="Wrap" Text="{Binding Fill, ElementName=Rectangle1, Mode=TwoWay, Converter={StaticResource ColorConverter}}"/> </StackPanel> </Grid> </UserControl> |