Window.GetWindow在设计时返回null

时间:2012-10-24 04:21:54

标签: .net wpf wpf-controls

我花了几个小时搞清楚为什么Window.GetWindow(this)在我的自定义控件中返回null。而且,它只发生在设计时。运行时很好。以下是重现问题的步骤:

步骤1:在VS2010中创建一个WPF应用程序项目,目标是.NET 4,名为“TestGetWindow”

步骤2:添加名为MyTextBox的自定义控件。以下是代码。

public class MyTextBox : TextBox
{
    public MyTextBox()
    {
        this.Loaded += new RoutedEventHandler(MyTextBox_Loaded);
    }
    void MyTextBox_Loaded(object sender, RoutedEventArgs e)
    {
        MessageBox.Show(Window.GetWindow(this) == null? "Window is NULL!" : "OK");
        DoTrace(this);
    }
}

此处未显示DoTrace()方法。它用于输出从this post复制的可视树和逻辑树的跟踪信息。它将跟踪消息输出到日志文件。

然后,在MainWindow.xaml中使用MyTextBox控件:

<Window x:Class="TestGetWindow.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:TestGetWindow"    
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <local:MyTextBox x:Name="textBox1" Height="23" HorizontalAlignment="Left" Margin="52,62,0,0" VerticalAlignment="Top" Width="120" />
    </Grid>
</Window>

现在全部保存,关闭Visual Studio中的MainWindow.xaml设计器/编辑器,构建项目,然后重新打开MainWindow.xaml。现在检查跟踪日志文件,它显示每个元素都没有父窗口:

========= VISUAL TREE FOR MyTextBox ============
MyTextBox has no window.
Grid has no window.
ContentPresenter has no window.
Grid has no window.
Border has no window.
WindowInstance has no window.
AdornerDecorator has no window.
Grid has no window.
Border has no window.
Border has no window.
DockPanel has no window.
Border has no window.
Grid has no window.
WindowInstance has no window.
Border has no window.
DesignerBackground has no window.
FormDesignerView has no window.
Viewport has no window.
ScrollContentPresenter has no window.
Grid has no window.
ScrollViewer has no window.
Grid has no window.
ContentPresenter has no window.
ContentRoot has no window.
========= LOGICAL TREE FOR MyTextBox ============
MyTextBox has no window.
Grid has no window.
WindowInstance has no window.
Border has no window.
DesignerBackground has no window.
FormDesignerView has no window.
Viewport has no window.
ScrollViewer has no window.
Grid has no window.
ContentRoot has no window.

但是在运行时,日志显示每个元素都有一个窗口。我错过了什么?为什么Window.GetWindow()总是在设计时返回null?

1 个答案:

答案 0 :(得分:0)

OK!我知道了。我不应该在我的自定义控件中在设计时调用Window.GetWindow()。我使用以下代码来解决我的问题:

if (System.ComponentModel.DesignerProperties.GetIsInDesignMode(this)) 
{
   return;
}