c# - How can I use an IValueConverter to bind to different properties of an object in WPF? -


i have property in view model has property of class has multiple properties e.g.

public class content {     public int selector { get; set; }     public int value1 { get; set; }     public int value2 { get; set; }     public int value3 { get; set; }     public int value4 { get; set; } }  public class viewmodel {     public content contentinstance { get; set; } } 

and want bind in xaml converter such value of selector determines value bound element e.g.

<textbox text="{binding contentinstance, converter="contentvalueconverter", targetnullvalue='', mode=twoway, updatesourcetrigger=propertychanged}"/> 

so far have:

public class contentvalueconverter : ivalueconverter {     public object convert(object value, type targettype, object parameter, cultureinfo culture)         {         var contentpart = value content;         if(contentpart == null) return;          switch(contentpart.selector)         {             case 1:                 return contentpart.value1;             //etc         }     }      public object convertback(object value, type targettype, object parameter, cultureinfo culture)     {         throw new notimplementedexception();     } } 

this works display value not save value model. prefer keep in ivalueconverter has added many places in codebase. value saving model appreciated.

your approach has 1 more flaw - changes made of content's properties not picked wpf, if content implements inotifypropertychanged.

if don't care then, theoretically, depending on scenario, store reference content object gets passed convert method , reuse in convertback. it's not clean nor wpfish, requires separate converter's instance per binding (so converter has defined inline, not resource).

so why don't implement proxy property in viewmodel instead?

public class viewmodel {     public content contentinstance { get; set; }     public int value     {                 {             switch (content.selector)             {                 case 1:                     return contentpart.value1;                 //etc             }         }         set         {             switch (content.selector)             {                 case 1:                     contentpart.value1 = value;                     break;                 //etc             }         }     } } 

then can bind directly it:

<textbox text="{binding value, mode=twoway}"/> 

clean , effective. if content implements inotifypropertychanged viewmodel can intercept , raise changed events value property too.


Comments

Popular posts from this blog

java - UnknownEntityTypeException: Unable to locate persister (Hibernate 5.0) -

python - ValueError: empty vocabulary; perhaps the documents only contain stop words -

ubuntu - collect2: fatal error: ld terminated with signal 9 [Killed] -