fbpx
Welcome, Guest
Username: Password: Remember me
Share your code snippets, screen shots etc. here
  • Page:
  • 1

TOPIC: WPF TextBox: implement a generic ValueConverter

WPF TextBox: implement a generic ValueConverter 1 year 5 months ago #3492

  wriedmann's Avatar Topic Author wriedmann Offline Posts: 1545
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
Wolfgang Riedmann
Meran, South Tyrol, Italy
This email address is being protected from spambots. You need JavaScript enabled to view it.
www.riedmann.it - docs.xsharp.it
Attachments:

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

  • Page:
  • 1