从后面的代码在wpf中启动自定义窗口不会绘制它的内容

时间:2013-08-30 05:11:35

标签: c# wpf window

在我的测试中,我创建了一个这样的简单类:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;

namespace Test
{
    public class MyCustomWindow: Window
    {

    }
}

这个类被编译成一个dll。 在另一个项目中,我尝试使用此自定义窗口,如下所示:

<Custom:MyCustomWindow x:Class="MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:Custom="clr-namespace:Test;assembly=Test"
    Title="MainWindow" Height="600" Width="1210" WindowState="Maximized" >

   <Grid Background="Blue">
       <Button Content="Button" HorizontalAlignment="Left" Margin="457,212,0,0" VerticalAlignment="Top" Width="75"/> 
   </Grid>

这个东西编译没有错误,并且当App.xaml文件中的“StartupUri”打开自定义窗口时(定义加载的第一个窗口),它可以很好地工作。

但是,如果我在StartupUri中设置其他窗口加载,并且:

MainWindow m = new MainWindow();
m.Activate();
m.Show();
this.Close();

CustomWindow将打开,但没有任何内容,没有按钮,没有蓝色网格 - 甚至没有标题。

任何解决方法?我需要做些什么来打开一个具有StartupUri相同行为的Window?

修改

我注意到MainWindow(或从MyCustomWindow派生的任何窗口)根本不能在构造函数中使用InitializeComponent()方法,因为它在上下文中不存在。奇怪的是,当使用StartupUri时,内容会正常加载而不会这样。

编辑2:

我认为问题正在发生,因为我无法将InitializeComponent()方法放在MyCustomWindow中。这解释了为什么MainWindow可以正常加载到StartupUri中:它直接从xaml文件加载,因此它在不需要InitializeComponent的情况下解析内容。

我开始考虑实现IComponentConnector接口,但我不知道如何做到这一点。

编辑3:

MainWindow.xaml.cs文件的代码隐藏是:

using Test;

namespace TestingCustomWindow
{
    public partial class MainWindow : MyCustomWindow
    {
        public MainWindow()
        {
              // Cannot use InitializeComponent here
        }
    }
}

2 个答案:

答案 0 :(得分:1)

我认为构造函数必须看起来像这样

public class MyCustomWindow: Window
{
    InitializeComponent();
}

答案 1 :(得分:1)

请使用Visual Studio添加新窗口 替换:窗口:MyCustomWindow。你将获得initializecomponent。您将在xaml中使用CustumWindow标记更新窗口标记

将其添加为答案,以便其他人可以使用它。

由于