如何从WPF中的非窗口类获得控制权?

时间:2010-07-30 16:28:50

标签: wpf

Application.Current.MainWindow。 ?

2 个答案:

答案 0 :(得分:4)

如果您的控件位于应用程序的主窗口中,则很可能需要将其转换为适当的类型。例如,如果您的“主窗口”名为Window1(默认命名),则可以执行以下操作:

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...
}

答案 1 :(得分:2)

另一个与上面Reed的回复非常相似的例子,这里是一个事件处理程序(app.xaml.cs),用于更新状态栏(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();
}