ivalueconverter value converter can convert one type to another type. For example, convert a value type to a string type and convert an image URL to an image type, you can also convert a value to a new value. In WPF, it is usually used for binding. The following is a simple example to see how ivalueconverter works.
first, we can see that ivalueconverter has two methods:
Public object convert (object value, type targettype, object parameter, system. globalization. cultureinfo culture);
Public object convertback (object value, type targettype, object parameter, system. globalization. cultureinfo culture);
for example, in terms of our most common page number conversion problem, usually the page number starts from 0, however, the display is displayed on the first page. You can use the converter to complete the process.
inherit the ivalueconverter interface:
Public class pageindexconvert: ivalueconverter {public int addvalue {Get; set;} public object convert (object value, type targettype, object parameter, system. globalization. cultureinfo culture) {int curentvalue = toint (value); curentvalue + = addvalue; return curentvalue;} public object convertback (object value, type targettype, object parameter, system. globalization. cultureinfo culture) {int curentvalue = toint (value); curentvalue-= addvalue; return curentvalue;} public int toint (object Value) {If (value = dbnull. value | value = NULL | string. isnullorempty (value. tostring () {return Int. minvalue;} Try {return system. convert. toint32 (value);} catch {return Int. minvalue ;}}}
use the prepared converter on the page:
<Window X: class = "testconvert. mainwindow "xmlns =" http://schemas.microsoft.com/winfx/2006/xaml/presentation "xmlns: x =" http://schemas.microsoft.com/winfx/2006/xaml "xmlns: Local =" CLR-namespace: testconvert "Title =" mainwindow "Height =" 350 "width =" 525 "> <grid. resources> <! -- Reference converter --> <local: pageindexconvert X: Key = "addoneconvert" addvalue = "1"/> </grid. resources> <textbox Height = "52" horizontalalignment = "Left" margin = "179,118, 152 "name =" textbox1 "verticalignment =" TOP "width =" "keydown =" numbertextbox_keydown "/> <! -- Use the converter --> <textblock Height = "44" horizontalalignment = "Left" margin = "181,202," name = "textblock1" text = "{binding elementname = textbox1, path = text, converter = {staticresource addoneconvert} "verticalalignment =" TOP "width =" 150 "/> <textblock Height =" 23 "horizontalalignment =" Left "margin =" 105,132, 0, 0 "name =" textblock2 "text =" input: "verticalalignment =" TOP "/> <textblock Height =" 23 "horizontalalignment =" Left "margin =" 105,202, 0, 0 "name =" textblock3 "text =": "verticalalignment =" TOP "/> </GRID> </WINDOW>
: enter a number and convert it to a specified value.
code download:
http://download.csdn.net/detail/yysyangyangyangshan/5416169