user1304153
user1304153

Reputation: 11

WPF Focus behavior issue

I have two views for e.g 'A'.Xaml and 'B'.Xaml . In A.Xaml I have a textbox and B.Xaml I Have a Button , on click of Button present in the 'B' View ,the focus should be set on the control (textBox) present in 'A'.Xaml(View). How to achieve this .I tried many ways uisng Focus behaviour,Focuselement,Focusable etc ,I see the main issue is How to set focus on control present in different view ,when action is performed in different view?Please reply .Thanks in advance Krishna

Upvotes: 0

Views: 391

Answers (2)

dball
dball

Reputation: 374

Try something like:

Application.Current.Dispatcher.Invoke(() =>
        {
            txtSomeTextBox.Focus();
        });

You may also want to try Application.Current.MainWindow to gain access into A.xaml.

Upvotes: 0

myermian
myermian

Reputation: 32515

You need to somehow have a reference to the A view from within your B view. Then you simply use an event on the Button in B

private void Button_Click(object sender, EventArgs e)
{
    windowA.txtSomeTextBox.Focus();
}

Something similar to that. I don't actually know what you named your controls, so those parts are probably wrong (since I guessed them).


Note, that this is just one way of doing it. There are many other ways of doing it, for exmaple... if you use the Prism framework you can use an EventAggregator to publish an event between two views that are unrelated, or from a viewmodel that binds the Button to a Command which publishes the event, and the subscriber (the view) captures that event and does what it needs to do. Etc. etc.

Upvotes: 1

Related Questions