0

Window.GetWindow(this) がカスタム コントロールで null を返す理由を理解するのに何時間も費やしました。そして、それは設計時にのみ発生しました。ランタイムは問題ありません。問題を再現する手順は次のとおりです。

手順 1: VS2010 で、.NET 4 を対象とする "TestGetWindow" という名前の WPF アプリケーション プロジェクトを作成します。

手順 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() メソッドはここには示されていません。この投稿からコピーされた、ビジュアルツリーとロジックツリーのトレース情報を出力するために使用されます。トレース メッセージをログ ファイルに出力します。

次に、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 に答える