WPF TextBox: implement a generic ValueConverter

Public forum to share code snippets, screen shorts, experiences, etc.
Post Reply
User avatar
wriedmann
Posts: 3753
Joined: Mon Nov 02, 2015 5:07 pm
Location: Italy

WPF TextBox: implement a generic ValueConverter

Post by wriedmann »

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:

Code: Select all

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:

Code: Select all

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
TextBoxConverterApp.zip
(4.64 KiB) Downloaded 50 times
Wolfgang Riedmann
Meran, South Tyrol, Italy
wolfgang@riedmann.it
https://www.riedmann.it - https://docs.xsharp.it
Post Reply