Generic converters for WPF converters

Source: Internet
Author: User

The translator in WPF is a very good data-type conversion solution, practical and powerful, and its role is to transform the source data into the type required by WPF itself, which is not aggressive to the data entities and will be used frequently in project engineering. So mastering the converter is a must for WPF development.

When I first contacted the converter, I didn't consider commonality, and every time I met a conversion requirement, I was going to create a new converter, and the converter in the project was a long way off.

This, of course, I can not tolerate, I decided to use a general purpose converter to replace the majority of the same nature of the conversion operation, by agreeing a set of parameter rules to adapt to different conversion scenarios, to achieve the purpose of the converter reuse.

Converters are available in two categories, IValueConverter (single-value converters) and Imultivalueconverter (multi-value converters)

Single-valued Universal converter objectconverter

Parameter rule "Compare value 1| comparison value 2:true return value: false return value"

In a closer look, this parameter rule is the same as the ternary expression, when the source data equals the comparison value 1 or the comparison value 2, returns true return value, otherwise returns false return value

With this rule, you can achieve the general conversion requirements, the Objectconverter source code is as follows

 public class Objectconverter:ivalueconverter {public Object Convert (object value, Type targetType, Object pa Rameter, CultureInfo culture) {string[] Parray = parameter. ToString (). ToLower (). Split (': '); The parameter character fragment Parray[0] is the comparison value, Parray[1] is true return value, Parray[2] is false return value if (value = = null) return parray[2]  ; If the data source is empty, the default returns False if the return value is (Parray[0].  Contains ("|")) Determine if there are multiple comparison values return parray[0]. Split (' | '). Contains (value. ToString (). ToLower ())?  PARRAY[1]: parray[2]; Multi-value comparison return parray[0]. Equals (value. ToString (). ToLower ())?  PARRAY[1]: parray[2];        Single Value comparison} public object Convertback (object value, Type targetType, object parameter, CultureInfo culture)            {var returnvalue = "Othervalue"; string[] Parray = parameter. ToString (). ToLower ().            Split (': ');            if (value = = null) return returnvalue; var valuestr = value. ToString (). ToLower ();           if (valuestr! = parray[1]) return returnvalue; else return parray[0]. Contains (' | ')? Parray[0]. Split (' | ')        [0]: parray[0]; }    }

Use of Objectconverter

1 <Converter:objectconverterx:key= "Objconverter"/>2 3 <BorderVisibility="{Binding panelstatus, Converter={staticresource objconverter},converterparameter=true:visible:collapsed} ">4 5 <BorderBackground="{Binding BgColor, Converter={staticresource objconverter},converterparameter=1:red:blue}">6 7 <TextBlockText="{Binding Type, Converter={staticresource OBJCONVERTER},CONVERTERPARAMETER=1|2:VIP member: ordinary member}"/>

Multi-valued Universal converter multiobjectconverter

Parameter rule "Compare Values by group: comparison criteria (&amp; or |) : True return Value: False return Value: Return value type enum "

The parameter rules of a multi-valued converter are slightly cumbersome, but similar to ternary expressions, except that there are more comparison conditions and return value enumeration types, where one asks why a single-value converter does not need to declare a return value enumeration and a multivalued converter needs it because the return value of a multivalued converter does not return the actual type, and the return type is invalidated. The default translator for WPF does not seem to play a role. I'm also working on this question, so first define a return value enumeration to convert the type of the return value. Let's just calculate a temporary solution.

1  Public classMultiobjectconverter:imultivalueconverter2     {3         /// <summary>4         ///Multi-value converters5         /// </summary>6         /// <param name= "values" >array of parameter values</param>7         /// <param name= "parameter" >8         /// <para>Parameters</para>9         /// <para>comparison values for each group: comparison criteria (&amp; or |): True return value: False return Value: Return value type enumeration</para>Ten         /// <para>v1;v2-1|v2-2;v3:&amp;:visible:collapsed:1</para> One         /// </param> A         /// <returns></returns> -          Public ObjectConvert (Object[] values, Type targetType,Objectparameter, System.Globalization.CultureInfo culture) -         { the             string[] param = parameter. ToString (). ToLower (). Split (':');//to fragment a parameter string -             string[] Comparevalues = param[0]. Split (';');//splitting a comparison value segment into arrays -             if(values.) Length! = comparevalues.length)//Compare the number of source data and comparison parameters -                 returnConvertvalue (param[3], param[4]); +             varTruecount =0;//number of results satisfying the condition -             varCurrentValue =string. Empty; +ilist<string> Currentparamarray =NULL; A              for(vari =0; I < values. Length; i++) at             { -CurrentValue = values[i]! =NULL? Values[i]. ToString (). ToLower ():string. Empty; -                 if(Comparevalues[i]. Contains ("|")) -                 { -                     //Current comparison value segment contains multiple comparison values -Currentparamarray = Comparevalues[i]. Split ('|');  inTruecount + = Currentparamarray.contains (currentvalue)?1:0;//satisfying condition, result +1 -                 } to                 Else +                 { -Truecount + = Comparevalues[i]. Equals (currentvalue)?1:0;//satisfying condition, result +1 the                 } *             } $Currentparamarray =NULL;Panax NotoginsengCurrentValue =string. Empty; -             varCompareresult = param[1]. Equals ("&") ? theTruecount = =values. Length: +Truecount >0;//Judging comparison results A             returnConvertvalue (compareresult? param[2]: param[3], param[4]); the         } +  -          Public Object[] Convertback (ObjectValue, type[] targettypes,Objectparameter, System.Globalization.CultureInfo culture) $         { $             Throw Newnotimplementedexception (); -         } -  the         Private ObjectConvertvalue (stringResultstringenumstr) -         {Wuyi             varConvertResult = (ConvertResult)int. Parse (ENUMSTR); the             if(ConvertResult = =convertresult. Display Type) -                 returnResult. Equals ("collapsed") ?Visibility.Collapsed:Visibility.Visible; Wu             if(ConvertResult = =convertresult. Boolean type) -                 returnSystem.Convert.ToBoolean (result); About             return NULL; Subsequent self-expansion $         } -  -         Private enumConvertResult -         { ADisplay Type =1, +Boolean type =2, theString type =3, -Integral type =4, $Decimal type =5, theBrush type =6, theStyle type =7, theTemplate type =8 the         } -}

Use of Mulitobjectconverter

1 <TextBlockText= "Test">2    <textblock.visibility>3         <multibindingConverter="{StaticResource Mobjconverter}"4 Converterparameter= "1|2;true:|:visible:collapsed:1">5              <BindingPath= "Filed1"/>6              <BindingPath= "Filed2"/>7         </multibinding>8     </textblock.visibility>9 </TextBlock>    

Single-valued general purpose converters and multi-valued general purpose converters have been completed, and readers can customize the Converterparameter rules according to their own needs to achieve flexible expansion. Welcome to Group Exchange 372754241

Generic converters for WPF converters

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.