MVVM How do I Set Focus on TextBox?

MVVM How do I Set Focus on TextBox?

Old forum URL: forums.lhotka.net/forums/t/10600.aspx


JonM posted on Monday, August 08, 2011

So I'm using Silverlight / CSLA 4.1 with a BxF setup.  When I call a add method on my ViewModel is creates a new object and the databinding works well for updating the UI.  The only issue is I need to focus on the main textbox.  Any idea on how to get this done or if CSLA or BxF have help for this?  The problem I see is that the ViewModel doesn't know anything about the UI and the UI is only databound to the ViewModel.  Is there anyway to use this binding to set the focused control?

RockfordLhotka replied on Monday, August 08, 2011

This is tricky. To be pure MVVM, you need something in the XAML that binds to a property of the viewmodel, and when the property value changes, then the thing in XAML sets the focus.

There is not (to my knowledge) any such thing in Silverlight XAML. WPF has a focus manager component - though I don't think it is powerful enough to solve this either.

In at least one project, I created a component to do this. I think I made it an attached property, but I don't remember for sure. In any case, it did what I describe here. It had a property that could be bound to a viewmodel property. When the viewmodel property was set to a certain value, my component set the focus in the UI.

Unfortunately I don't remember whether this was for a client project, or a CSLA demo, or a talk I did at VS Live - so I'm not sure where to find that code :(

On the positive side, it wasn't hard code. Writing a UI control or attached property is not hard - especially if all it does is call the Focus method when a property changes.

MichelRenaud replied on Tuesday, August 09, 2011

Off the top of my head - and keep in mind that I'm now just starting with MVVM: When your viewmodel handles the add method, it could dispatch a message that's handled by the view (basically telling the view "that field - whatever control it is - should have the focus").  The view can then do whatever it has to to give the textbox focus.  The viewmodel then has no knowledge of the underlying UI.

As to how to set the focus in Silverlight, that I do not know.  I only use WPF.

Copyright (c) Marimer LLC