WPF - Chuyển Đổi Dữ Liệu Với IValueConverter

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 8

WPF Data Binding: Chuyn i d liu vi IValueConverter

C nhng trng hp bn cn thc hin mt binding phc tp nh


chuyn i, tnh ton, tm kim t gi tr ny sang gi tr khc. lm c iu ny, bn
cn to mt lp converter hin thc interfaceIValueConverter v gn th hin ca lp ny
cho property Binding.Converter.

Gii thiu
Interface IValueConverter bao gm hai phng thc l Convert() v ConvertBack()
chuyn i qua li gia binding source v binding target. Thng thng bn ch cn hin
thc phng thc Convert() chuyn t binding source sang binding target, i vi nhng
trng hp s dng binding mode l TwoWay hay OneWayToSource mi cn hin thc
phng thc ConvertBack().

i vi cc trng hp khng th chuyn c gi tr,

bn nn tr v gi tr DependencyProperty.UnsetValue.

i vi cc lp converter, bn

nn dng [ValueConversionAttribute] xc nh kiu d liu s dng cho vic chuyn i.

Phng thc IValueConverter.Convert


C php
ObjectConvert(
Objectvalue,
TypetargetType,
Objectparameter,
CultureInfoculture
)
Tham s
value: Gi tr cn chuyn i ly t binding source.

targetType: Kiu d liu ca binding target property.

parameter: Tham s cn thit

culture: p dng nh dng vi mi nn vn ha khc nhau.


Gi tr tr v
Kt qu ca vic chuyn i.

V d 1
V d sau thc hin mt binding hai chiu chuyn (tnh ton) mt s thnh cn bc hai

ca n v ngc li.
<Windowx:Class="WpfApplication1.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clrnamespace:WpfApplication1"
Title="SquareRootConverterDemo"Height="300"Width="400">
<Window.Resources>
<local:SquareRootConverterx:Key="mySquareRootConverter"/>
</Window.Resources>
<StackPanel>
<TextBoxx:Name="textBox1"/>

XAML:

<LabelContent="SquareRoot:"/>
<TextBoxText="{BindingElementName=textBox1,Path=Text,
UpdateSourceTrigger=PropertyChanged,Converter={StaticResource
mySquareRootConverter}}"/>
</StackPanel>
</Window>
C# (code-behind):
[ValueConversion(typeof(double),typeof(double))]
publicclassSquareRootConverter:IValueConverter
{
publicobjectConvert(objectvalue,TypetargetType,objectparameter,
CultureInfoculture)
{
doublenumber;
if(double.TryParse(value.ToString(),outnumber))
{
returnMath.Sqrt(number);
}
returnDependencyProperty.UnsetValue;
}

publicobjectConvertBack(objectvalue,TypetargetType,objectparameter,
CultureInfoculture)

{
doublenumber;
if(double.TryParse(value.ToString(),outnumber))
{
returnnumber*number;
}
returnDependencyProperty.UnsetValue;
}
}

V d 2
Converter mc nh ca WPF c th t ng chuyn i t nhiu kiu d liu khc nhau, v
d nh kiu string trong property TextBox.Text c th c chuyn thnh kiu Brush cho

property StackPanel.Background.
XAML:
<Windowx:Class="WpfApplication1.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="StringColorConverterDemo"

Height="300"Width="300">
<StackPanelBackground="{BindingElementName=txtColor,Path=Text}">
<TextBoxx:Name="txtColor">Green</TextBox>
<LabelContent="{BindingElementName=txtColor,Path=Text}"/>
</StackPanel>
</Window>

V d 3
thc hin chuyn i sang nhiu kiu d liu khc nhau, bn cn phi s dng tham
stargetType ca phng thc Convert(). V d sau thc hin chuyn mt chui tn mu
sc (ting Anh) sang Brush hoc tn mu sc (ting Vit) da vo tham s targetType ny:

XAML:
<Windowx:Class="WpfApplication1.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clrnamespace:WpfApplication1"

Title="StringColorConverterDemo"
Height="300"Width="300">
<Window.Resources>
<local:StringColorConverterx:Key="myStringColorConverter"/>
</Window.Resources>
<StackPanelBackground="{BindingElementName=txtColor,
Path=Text,Converter={StaticResourcemyStringColorConverter}}">
<TextBoxx:Name="txtColor">Green</TextBox>
<LabelContent="{BindingElementName=txtColor,
Path=Text,Converter={StaticResourcemyStringColorConverter}}"/>
<TextBoxText="{BindingElementName=txtColor,
Path=Text,Converter={StaticResourcemyStringColorConverter}}"/>
</StackPanel>
</Window>
C# (code-behind):
publicclassStringColorConverter:IValueConverter
{
publicobjectConvert(objectvalue,TypetargetType,objectparameter,
System.Globalization.CultureInfoculture)
{
if(targetType==typeof(string))
{
stringstr=valueasstring;

if(str=="Red")
return"";
elseif(str=="Green")
return"Xanhl";
elseif(str=="Blue")
return"Xanhbin";
else
return"Khngbit";

}
elseif(targetType==typeof(Brush))
{
stringstr=valueasstring;
try
{
Colorcolor=(Color)ColorConverter.ConvertFromString(str);
returnnewSolidColorBrush(color);
}
catch
{
returnDependencyProperty.UnsetValue;

}
}
else
return"DependencyProperty.UnsetValue";//return
DependencyProperty.UnsetValue;
}

publicobjectConvertBack(objectvalue,TypetargetType,objectparameter,
System.Globalization.CultureInfoculture)
{
thrownewNotImplementedException();
}
}
http://yinyangit.wordpress.com

You might also like