0

我花了几个小时弄清楚为什么 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() 方法未在此处显示。用于输出可视化树和逻辑树的trace信息,复制自本帖。它将跟踪消息输出到日志文件。

然后,在 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?

4

1 回答 1

0

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

if (System.ComponentModel.DesignerProperties.GetIsInDesignMode(this)) 
{
   return;
}
于 2012-10-24T05:01:01.700 回答