2

C# で WPF アプリケーションを作成しています。

MainWindowクラスから継承するクラスがありSystem.Windows.Windowます。

次に、実行時にロードするディスクに xaml ファイルがあります。

<Window x:Class="MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="I want to load this xaml file">
</Window>

実行時にそのxamlファイルをロードするにはどうすればよいですか? つまり、MainWindow クラスで前述の xaml ファイルを正確に使用する必要があるため、ウィンドウに子を追加するため MainWindowのメソッドを使用したくありませんが、そのパラメーターも置き換えAddChildたいと考えています。どうすればこれを達成できますか?Window

4

2 に答える 2

0

簡単な答え:-いいえ、の内側からを置き換えることはできません。「ねえ、すべてをこの他のウィンドウに置き換えてください」という派生オブジェクトの内部にアクセスできるものはありません。WindowWindowWindow

より長い答え:-しかし、あなたはこのような愚かなことをすることができます:

private void ChangeXaml()
{
    var reader = new StringReader(xamlToReplaceStuffWith);
    var xmlReader = XmlReader.Create(reader);
    var newWindow = XamlReader.Load(xmlReader) as Window;    
    newWindow.Show();
    foreach(var prop in typeof(Window).GetProperties())
    {
        if(prop.CanWrite)
        {
            try 
            {
                // A bunch of these will fail. a bunch.
                Console.WriteLine("Setting prop:{0}", prop.Name);
                prop.SetValue(this, prop.GetValue(newWindow, null), null);
            } catch
            {
            }
        }
    }
    newWindow.Close();
    this.InvalidateVisual();
}
于 2013-03-22T17:13:43.153 に答える