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

WPF TextBox: how to implement a Value property like in VO - Try 1

  • Wolfgang Riedmann
  • Wolfgang Riedmann's Avatar Topic Author
  • Offline
More
1 year 3 weeks ago - 1 year 3 weeks ago #1 by Wolfgang Riedmann
When working in WPF, I was missing the possibility to assign a numeric or date value to a textbox and have the same type of value returned - the TextBox has only a :Text property that returns a text.
Using MVVM, you can assign also numeric or date values, but the way back is not in your control.
My first try was to implement a :Value property and detect the type of the value automatically:
property _value as object
  get 
    return _oValue
  end get
  set
    _oValue := value
    self:_SetType( oValue )
  end set
end property

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

In the return the conversion can be made using Reflection:
private method __Update() as void
local oValue 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[]
	
aTypes 	:= <System.Type>{ TypeOf( string ), ( ( System.Type ) _oValueType ):MakeByRefType() }
oInfo := _oValueType:GetMethod( "TryParse", aTypes )
cTextValue := self:Text  
oValue := null
aParameters := <object>{ cTextValue, oValue }
lSuccess := ( logic ) oInfo:Invoke( null, aParameters )
if lSuccess
  oValue := aParameters[__ARRAYBASE__+1]
  self:Value := oValue     
  _cTextValue := cTextValue  
else
  self:Text := _cTextValue
endif
	
return

You can find the complete implementation together with a sample attached to this message as XIDE export file.

But the shown solution works well if you are using WPF without MVVM - in the next days I will show a IMHO better solution based on a generic TypeConverter.

Wolfgang
Attachments:
Last edit: 1 year 3 weeks ago by Wolfgang Riedmann.

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

More
1 year 2 weeks ago #2 by Phil Hepburn
Hi Wolfgang,

Value Converters are your friends.

It is too late tonight to send anything more detailed, but I have some good examples somewhere in my code.

I came late to Value Converters and wished I had found them sooner ;-0((

Hope you had a joyful Christmas - a Happy New Year to you and all forum readers.

Cheers,
Phil.
Wales, UK.

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

  • Wolfgang Riedmann
  • Wolfgang Riedmann's Avatar Topic Author
  • Offline
More
1 year 2 weeks ago #3 by Wolfgang Riedmann
Hi Phil,

as I wrote: that was a first try, and I have a better and simpler sample based on a generic value converter that uses some code from this sample.

I will post the other sample tomorrow, if I have time (currently I'm on holiday on the Azores Islands).

Wolfgang

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