WPF TextBox: implement a generic ValueConverter
Posted: Fri Dec 29, 2017 8:41 am
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:
The use of this class is very simple:
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
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
Code: Select all
oBinding := Binding{ "Server." + oTextBox:Name }
oBinding:ValidatesOnDataErrors := true
oBinding:UpdateSourceTrigger := UpdateSourceTrigger.PropertyChanged
oBinding:Converter := ExtendedValueConverter{}
oTextBox:SetBinding( TextBox.TextProperty, oBinding )
As always, you can find the complete implementation together with a sample attached to this message as XIDE export file.
Wolfgang