Eldar
Eldar

Reputation: 872

How get control from non-window class in WPF?

Application.Current.MainWindow. ?

Upvotes: 0

Views: 420

Answers (2)

Major Malfunction
Major Malfunction

Reputation: 113

Another example that's very similar to Reed's reply above, here's an event handler (app.xaml.cs) that updates text displayed in a status bar (MainWindow.xaml):

private void Control_GotFocus(object sender, RoutedEventArgs e)
{
    // Do not select text for read-only text boxes.
    if ((sender is TextBox) && (!(sender as TextBox).IsReadOnly))
    {
        (sender as TextBox).SelectAll();
    }

    // Update status bar text to display control tag value.
    (Application.Current.MainWindow.FindName("statusBarTextBlock")
        as TextBlock).Text = (sender as Control).Tag.ToString();
}

Upvotes: 2

Reed Copsey
Reed Copsey

Reputation: 564333

If your control is in the main window of your application, you most likely need to cast it to the appropriate type. For example, if your "main window" is named Window1 (default naming), you could do:

Window1 myWindow = Application.Current.MainWindow as Window1;
if (myWindow != null)
{
     Button myButton = myWindow.button1; // Use your control here...
     myButton.IsEnabled = true; // Do something with the control here...
}

Upvotes: 4

Related Questions