Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a WPF converter access the control to which it is bound?

Tags:

binding

wpf

Long version: I have a simple WPF converter than does date conversions for me. The converter basically checks the date and formats it in dd/M/yyyy format. The converter does some smarts with the handling of the date which means that the user could type "23061971" and the value will be converted to "23/06/1971".

All this is trivial and working. The problem is that when I update the value, it does not update the caret position. Assume "|" is the caret and the user types "23061971|" then a millisecond later it is updated to "230619|71".

What I'd like to do is detect if the caret at the end of the value - if so, shift it to the end of the edit field once the new value has been updated. In order to do this, I'll need access to the edit control to which the converter is attached.

Short version: From A WPF converter, can I get a reference to the control that is bound to that converter?

like image 866
dave Avatar asked Mar 28 '11 04:03

dave


2 Answers

Here is an excellent article on how to get direct access to the control from within a converter: http://social.technet.microsoft.com/wiki/contents/articles/12423.wpfhowto-pass-and-use-a-control-in-it-s-own-valueconverter-for-convertconvertback.aspx

Essentially:

<MultiBinding Converter="{StaticResource MyConverter}" >
    <Binding RelativeSource="{RelativeSource Self}" Mode="OneTime"/>
    <Binding Path="MyValue2" />
</MultiBinding>

in the converter values[0] will be your control, ready for casting and values[1] would be the data that you are binding.

like image 81
ergohack Avatar answered Oct 03 '22 10:10

ergohack


In a ValueConverter you can't get access to the control - however you can get access if you use a multibinding with a multivalueconverter.

In the multibinding the first binding is your binding as now - without the converter. The second binding you bind to the control itself - there you go acces to the control.

I have used this approach to gain other things also - you can make "dummy" bindings to properties you want to trigger updates, i.e. if you bind to the control itself you will only get updated if it changes, not if a property does - so create dummybindings for those.

like image 40
Rune Andersen Avatar answered Oct 03 '22 10:10

Rune Andersen