Có những trường hợp bạn cần thực hiện một binding phức tạp như chuyển đổi, tính toán, tìm kiếm từ giá trị này sang giá trị khác. Để làm được điều này, bạn cần tạo một lớp converter hiện thực interface IValueConverter và gán thể hiện của lớp này cho property Binding.Converter.
Giới thiệuInterface IValueConverter bao gồm hai phương thức là Convert() và ConvertBack() để chuyển đổi qua lại giữa binding source và binding target. Thông thường bạn chỉ cần hiện thực phương thức Convert() để chuyển từ binding source sang binding target, đối với những trường hợp sử dụng binding mode là TwoWay hay OneWayToSource mới cần hiện thực phương thức ConvertBack(). - Đối với các trường hợp không thể chuyển được giá trị, bạn nên trả về giá trị DependencyProperty.UnsetValue. - Đối với các lớp converter, bạn nên dùng [ValueConversionAttribute] để xác định kiểu dữ liệu sử dụng cho việc chuyển đổi. Phương thức IValueConverter.ConvertCú pháp Object Convert( Object value, Type targetType, Object parameter, CultureInfo culture ) Tham số
Giá trị trả vềKết quả của việc chuyển đối. Ví dụ 1Ví dụ sau thực hiện một binding hai chiều để chuyển (tính toán) một số thành căn bậc hai của nó và ngược lại. <Window x:Class="WpfApplication1.Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:WpfApplication1" Title="SquareRootConverter Demo" Height="300" Width="400"> <Window.Resources> <local:SquareRootConverter x:Key="mySquareRootConverter"/> </Window.Resources> <StackPanel> <TextBox x:Name="textBox1" /> <Label Content="Square Root:" /> <TextBox Text="{Binding ElementName=textBox1, Path=Text, UpdateSourceTrigger=PropertyChanged, Converter= {StaticResource mySquareRootConverter}}" /> </StackPanel> </Window> C# (code-behind): [ValueConversion(typeof(double), typeof(double))] public class SquareRootConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { double number; if(double.TryParse(value.ToString(),out number)) { return Math.Sqrt(number); } return DependencyProperty.UnsetValue; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { double number; if (double.TryParse(value.ToString(), out number)) { return number*number; } return DependencyProperty.UnsetValue; } } Ví dụ 2Converter mặc định của WPF có thể tự động chuyển đổi từ nhiều kiểu dữ liệu khác nhau, ví dụ như kiểu string trong property TextBox.Text có thể được chuyển thành kiểu Brush cho property StackPanel.Background. <Window x:Class="WpfApplication1.Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="StringColorConverter Demo" Height="300" Width="300"> <StackPanel Background="{Binding ElementName=txtColor, Path=Text}"> <TextBox x:Name="txtColor">Green</TextBox> <Label Content="{Binding ElementName=txtColor, Path=Text}"/> </StackPanel> </Window> Ví dụ 3Để thực hiện chuyển đổi sang nhiều kiểu dữ liệu khác nhau, bạn cần phải sử dụng tham số targetType của phương thức Convert(). Ví dụ sau thực hiện chuyển một chuỗi tên màu sắc (tiếng Anh) sang Brush hoặc tên màu sắc (tiếng Việt) dựa vào tham số targetType này: <Window x:Class="WpfApplication1.Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:WpfApplication1" Title="StringColorConverter Demo" Height="300" Width="300"> <Window.Resources> <local:StringColorConverter x:Key="myStringColorConverter"/> </Window.Resources> <StackPanel Background="{Binding ElementName=txtColor, Path=Text,Converter={StaticResource myStringColorConverter}}"> <TextBox x:Name="txtColor">Green</TextBox> <Label Content="{Binding ElementName=txtColor, Path=Text,Converter={StaticResource myStringColorConverter}}"/> <TextBox Text="{Binding ElementName=txtColor, Path=Text,Converter={StaticResource myStringColorConverter}}"/> </StackPanel> </Window> C# (code-behind): public class StringColorConverter:IValueConverter { public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { if(targetType == typeof(string)) { string str = value as string; if(str=="Red") return "Đỏ"; else if(str=="Green") return "Xanh lá"; else if(str=="Blue") return "Xanh biển"; else return "Không biết"; } else if(targetType == typeof(Brush)) { string str = value as string; try { Color color= (Color)ColorConverter.ConvertFromString(str); return new SolidColorBrush(color); } catch { return DependencyProperty.UnsetValue; } } else return "DependencyProperty.UnsetValue"; // return DependencyProperty.UnsetValue; } public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { throw new NotImplementedException(); } } http://yinyangit.wordpress.com Related articles |
WPF – Data Binding: Chuyển đổi dữ liệu với IValueConverter
Ý kiến bạn đọc
Tin tức khác
WPF – Giới thiệu về Animation
- 6/8/2012
WCF – Self-hosted Service đơn giản
- 13/4/2012
WCF – Một số khái niệm cơ bản
- 10/4/2012
WPF – Tùy biến TabControl
- 28/3/2012
WPF – Tìm hiểu về ContentPresenter
- 28/3/2012
WPF – 2D Matrix Transformation
- 28/3/2012
WPF – 2D Transformations
- 28/3/2012
WPF – Multi Language với Binding và ResourceDictionary
- 28/3/2012
WPF – Sử dụng Resource Dictionary
- 26/3/2012
WPF – Tạo Custom Validation Rule
- 26/3/2012
Tin tiêu điểm
-
WPF – Data Validation (103,373)
-
WPF – Control Template (80,323)
-
WPF – Tùy biến TabControl (70,541)
-
WPF – Data Binding và Collection: Sorting, Filtering, Grouping (22,458)
-
WPF – Read-Only Attached Dependency Property (16,364)
-
WPF – Multi Language với Binding và ResourceDictionary (10,196)
-
WPF – Data Binding cơ bản (8,993)
-
WPF – Tạo Custom Validation Rule (8,983)
-
WPF – 2D Transformations (8,266)
-
WPF – Giới thiệu về Animation (7,510)
Gallery
Text Links
Thiết kế logo chuyên nghiệp Insky
DAFABET
W88 w88b.com/dang-ky-tai-khoan-w88
W88
ca do bong da online
DAFABET
W88 w88b.com/dang-ky-tai-khoan-w88
W88
ca do bong da online
Tags
asp.net
JavaScript
Lập trình
Cơ sở dữ liệu
jquery
Csharp
Ajax
Thủ thuật
JavaScript
menu
Sql Server
Lập trình C#
WebService
stty
Sql
Phân trang
Rewrite
Mã hoá
Backup
Thủ thuật lập trình
Store procedure
Accordion
Validation
Store
Upload
Slide
jQueryPlugin
StoreProcedure
Regular Expression
Regex
android
Quick and snow
HTML5
WPF
WCF
Copyright © 2011 - 2012 vietshare.vn
by
phamkhuong102@gmail.com doanhkisi2315@gmail.com. All rights reserved.