WPF value Converter

Source: Internet
Author: User

I. Summary

This article demonstrates the application of the WPF value converter through examples, and explains the knowledge points of the WPF value converter during the demonstration.

 

Ii. instance demonstration

1. Create the WPF Application converterexp. The program structure is shown in.

 

Figure 1 program structure

Shows the main screen of the program.

 

Figure 2 Main Program Screen

Program completion function:

You can change the background value of the textblock control by changing the selected items of the ComboBox control.

The items available in the drop-down list of the ComboBox control include "red", "green", and "blue". The selected items are "red" by default ".

The Default background value of the textblock control is "red ".


2. Create a value converter class colorconverter. The class file name is colorconverter. CS.

In the WPF binding model, you can use a value converter to convert a value from one type to another.

In this example, the value converter colorconverter converts integer data to the solidcolorbrush type data.

The solidcolorbrush type indicates a solid color paint brush. After you bind an instance of the solidcolorbrush type with the background attribute of the textblock control, you can set the background color of the textblock control.

The detailed code of the colorconverter class is as follows.

//************************************** ********************* // Ivalueconverter interface sample code // Author: may 3, May /// Date: 2014/08/03 /// using system; using system. windows. data; using system. windows. media; namespace converterexp {public class colorconverter: ivalueconverter {public static color [] colorcollection = new color [] {color. fromrgb (255, 0, 0), // red color. fromrgb (0,255, 0), // green color. fromrgb (0,0, 255) // blue}; public object convert (object value, type targettype, object parameter, system. globalization. cultureinfo culture) {If (value = NULL) {return New solidcolorbrush (colorcollection [0]);} Try {return New solidcolorbrush (colorcollection [(INT) value]);} catch (exception) {return New solidcolorbrush (colorcollection [0]) ;}} public object convertback (object value, type targettype, object parameter, system. globalization. cultureinfo culture) {Throw new notimplementedexception ();}}}
The value converter associated with the binding must implement the ivalueconverter interface. The ivalueconverter Interface contains the convert and convertback methods. Therefore, both the convert and convertback methods must be implemented.

The difference between the convert and convertback methods is that the convert method converts the value from the bound data source to the bound destination. The convertback method converts the value from the bound destination to the bound data source. Therefore, if the binding mode is one-time binding or one-way binding, you only need to complete the value conversion in the implementation of the convert method; if it is a two-way binding, you need to complete value conversion in the implementation of the convert and convertback methods at the same time.

In this example, the binding mode is unidirectional binding. Therefore, you only need to complete the value conversion in the implementation of the convert method. In the implementation of the convertback method, besides throwing notimplementedexception exception, you do not need to complete any other work.

The convert method of the colorconverter class in the instance. At the beginning, the passed value is compared with null. If the value is null, the first color value in colorcollection is used to initialize the solidcolorbrush object and return it; if the value is not null, the value is forcibly converted to an integer, And the converted integer value is used as the index to obtain the color value in the colorcollection to initialize the solidcolorbrush object and return it; if an exception occurs in the method, the first color value in colorcollection is also used to initialize the solidcolorbrush object and return it.

 

3. Create a converterviewmodel class. The class file name is converterviewmodel. CS.

In the converterviewmodel class, data sources used for the main program screen are defined.

The detailed code is as follows.

//************************************** ********************* // Ivalueconverter interface sample code // Author: may 3, May /// Date: 2014/08/03 /// using system. collections. generic; namespace converterexp {public class converterviewmodel {public ilist <colorinfo> colorlist {Get; set;} public int selectedcolor {Get; set;} public converterviewmodel () {colorlist = new list <colorinfo> () {New colorinfo () {id = 0, name = "red"}, new colorinfo () {id = 1, name = "green"}, new colorinfo () {id = 2, name = "blue" }}; selectedcolor = 0 ;}} public class colorinfo {public int ID {Get; set ;}public string name {Get; Set ;}}}
The colorlist attribute is used to specify the selection items in the ComboBox control drop-down list (A colorinfo instance represents a selection item), and The selectedcolor attribute is used to specify the selected items of the ComboBox control.

 

4. Implement the main screen of the program

4.1 mainwindow. XAML

<Window X: class = "converterexp. mainwindow "xmlns =" http://schemas.microsoft.com/winfx/2006/xaml/presentation "xmlns: x =" http://schemas.microsoft.com/winfx/2006/xaml "xmlns: localutil =" CLR-namespace: converterexp "Title =" converter Demo "Height =" 350 "width =" 525 "windowstyle =" toolwindow "> <grid. resources> <localutil: colorconverter X: Key = "colorconverter"/> </grid. resources> <grid. rowdefinitions> <rowdefinition> </rowdefinition> <strong> </rowdefinition> <rowdefinition </rowdefinition> </grid. rowdefinitions> <grid. columndefinitions> <columndefinition> </columndefinition> <strong> </columndefinition> <columndefinition> </columndefinition> </grid. columndefinitions> <label content = "color:" grid. row = "3" grid. column = "1" margin = ","/> <textblock background = "{binding selectedvalue, elementname = combobox_colorselect, converter = {staticresource colorconverter}" grid. row = "3" grid. column = "2" Height = "25" width = "80" margin = ","> </textblock> <ComboBox cursor = "hand" X: name = "combobox_colorselect" Height = "25" width = "80" itemssource = "{binding colorlist}" selectedvaluepath = "ID" displaymemberpath = "name" selectedvalue = "{binding selectedcolor} "grid. row = "3" grid. column = "3" margin = ","> </ComboBox> </GRID> </WINDOW>

4.2 mainwindow. XAML. CS

//************************************** ********************* // Ivalueconverter interface sample code // Author: may 3, May /// Date: 2014/08/03 /// using system. windows; namespace converterexp {// <summary> // mainwindow. interaction logic of XAML // </Summary> Public partial class mainwindow: window {public mainwindow () {initializecomponent (); this. datacontext = new converterviewmodel ();}}}

In the mainwindow. XAML. CS code, use the code "This. datacontext = new converterviewmodel ()" to set the data source to bind to the main screen.

The following content in the mainwindow. XAML file is related to the topic of the article. The following describes the content in this section.

<TextBlock Background="{Binding SelectedValue,ElementName=ComboBox_ColorSelect,Converter={StaticResource ColorConverter}}" Grid.Row="3" Grid.Column="2" Height="25" Width="80" Margin="0,7,0,7"></TextBlock><ComboBox Cursor="Hand" x:Name="ComboBox_ColorSelect" Height="25" Width="80" ItemsSource="{Binding ColorList}" SelectedValuePath="ID"  DisplayMemberPath="Name" SelectedValue="{Binding SelectedColor}" Grid.Row="3" Grid.Column="3"  Margin="0,7,0,7"></ComboBox>

By reading the code, you can see that:

The colorlist attribute in the data source is bound to the itemssource attribute of ComboBox, so that the ComboBox drop-down list contains the selected items "red" "green" and "blue ";

The selectedcolor attribute in the data source is bound to the selectedvalue attribute of ComboBox. When selectedcolor is initialized, the value is 0, indicating that ComboBox is selected as the first item by default and the value is "red ";

The selectedvaluepath attribute of ComboBox is bound to the ID attribute of the colorinfo instance. The displaymemberpath attribute of ComboBox is bound to the name attribute of the colorinfo instance. In this way, when you change the selected item of ComboBox, the selectedvalue property saves the ID of the selected item, while the screen displays the name of the selected item.

The background attribute of the textblock control is bound to the selectedvalue attribute of the ComboBox control. In this way, when the selected items in the ComboBox control change, the background value of the textblock control also changes. For example, when the selected color of the ComboBox control is "red", the value of the selectedvalue attribute of the ComboBox control is 0, so that the binding value of the background attribute of the textblock control is 0; when the selected color of the ComboBox control is "green", the selectedvalue attribute value of the ComboBox control is 1, so that the binding value of the background attribute of the textblock control is 1. At the same time, the value converter is used to convert the value. When the value of background changes to 0, the value converter converts 0 to the corresponding solidcolorbrush object, and use the converted solidcolorbrush object to complete the binding operation.

 

Summary

In the binding of WPF, you can use a value converter to convert a value from one type to another.

The value converter must implement the convert and convertback methods of the ivalueconverter interface.

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.