views:

141

answers:

1

I need code that will force Silverlight to commit the focused element (in my case a TextBox, but it could be anything). In WPF I use

        public static void CommitFocusedElement() {
        UIElement element = Keyboard.FocusedElement as UIElement;
        if (element != null) {
            TraversalRequest request = new TraversalRequest(FocusNavigationDirection.Next);
            FocusNavigationDirection directionBack = FocusNavigationDirection.Previous;
            if (!element.MoveFocus(request)) {                    
                request = new TraversalRequest(FocusNavigationDirection.Previous);
                directionBack = FocusNavigationDirection.Next;
                element.MoveFocus(request);
            }
            if (element.Focusable)
            {
                element.Focus();
            }
            else
            {
                element.MoveFocus(new TraversalRequest(directionBack));
            }
        }
    }

But several parts of this code is not Silverlight compatible. Can anyone point me to a Silverlight alternative?

Thanks.

+1  A: 

I'm assuming you want to update the source of a binding. If you're not, you probably should.

BindingExpression expression = textBox1.GetBindingExpression(TextBox.TextProperty);
expression.UpdateSource();
Eric Mickelsen
Thanks. If I don't know the exact element I want to update, is there a way to enumerate through all the element on the active control/window?
JeffN825
@jeffn825: You can iterate over the children of an element using the VisualTreeHelper: http://msdn.microsoft.com/en-us/library/ms635657(v=VS.95).aspx, but I doubt that's necessary. All sources should be updated automatically once the user clicks or tabs anywhere.
Eric Mickelsen
Doesn't seem to be happening. Specifically, I have a user typing into a textbox, then they hit enter. This should programmatically launch a new form using the info from the textbox...but the textbox doesn't seem to have committed the value. There are many textboxes though, so I don't know at runtime which textbox the user was typing into when they hit enter...
JeffN825
@jeffn825: That's just because the focus has yet to leave the text box when you're doing your processing. Just call Focus on some other element (and maybe call UpdateLayout), before you trust the data from the textboxes.
Eric Mickelsen
I already tried calling Focus on the parent Window and that didn't seem to do the trick...any idea why?
JeffN825
@jeffn825: It could be because the textbox is contained within the window and therefore doesn't actually lose focus.
Eric Mickelsen
@jeffn825: If your form has an OK button, or similar, try giving focus to that first and then calling UpdateLayout on the window.
Eric Mickelsen