fbpx
× Share your code snippets, screen shots etc. here

WPF TextBox: implement a generic ValueConverter

  • Wolfgang Riedmann
  • Wolfgang Riedmann's Avatar Topic Author
  • Offline
More
1 year 2 weeks ago #1 by Wolfgang Riedmann
WPF TextBox: implement a generic ValueConverter was created by Wolfgang Riedmann
After working a while with my ValueTextBox class, I have researched a bit more and found an even simpler mode to implement what I needed - without the need to write a new subclass for the TextBox.
The key was to use a ValueConverter and reusing some of the code I wrote for the ValueTextBox class:
using System.Windows.Data

class ExtendedValueConverter implements IValueConverter
  protect _oValueType as Type     

constructor()
  return
	
method Convert( oValue as object, oType as System.Type, oParameter as object, oCulture as System.Globalization.CultureInfo ) as object
local oInfo as System.Reflection.MethodInfo
local lSuccess as logic
local aParameters as object[]
local cTextValue as string
local aTypes as System.Type[]       
local oResult as object
	
oResult := oValue
	
aTypes := <System.Type>{ TypeOf( string ), ( ( System.Type ) _oValueType ):MakeByRefType() }
oInfo := _oValueType:GetMethod( "TryParse", aTypes )
if oInfo != null                 
  cTextValue := oValue:ToString()
  oResult := null
  aParameters := <object>{ cTextValue, oResult }
  lSuccess := ( logic ) oInfo:Invoke( null, aParameters )
  if lSuccess
    oResult := aParameters[__ARRAYBASE__+1]
  endif
endif    
	
return oResult
	
method ConvertBack( oValue as object, oType as System.Type, oParameter as object, oCulture as System.Globalization.CultureInfo ) as object
local cReturn as object  

self:_SetType( oValue )
cReturn := oValue:ToString()
	
return cReturn
	
private method _SetType( oValue as object ) as void 
	
_oValueType := oValue:GetType()
	
return

end class

The use of this class is very simple:
oBinding := Binding{ "Server." + oTextBox:Name } 
oBinding:ValidatesOnDataErrors := true
oBinding:UpdateSourceTrigger := UpdateSourceTrigger.PropertyChanged
oBinding:Converter := ExtendedValueConverter{}
oTextBox:SetBinding( TextBox.TextProperty, oBinding )
and can be used both in XAML or in your own control class that does the binding.

As always, you can find the complete implementation together with a sample attached to this message as XIDE export file.

Wolfgang
Attachments:

Please Log in or Create an account to join the conversation.