Is it possible to use XamlReader.Load or InitializeFromXaml from a WPF window to define a window?

I want to create some library code that will be included in WPF applications. The library may display a window, as appropriate. I can define Window in XAML, but I would like to treat XAML as a template. At runtime, at window creation time, so that it can be displayed, I want to replace certain tags in the Xaml template with values ​​defined at runtime.

I want to do something like this:

public partial class DynamicXamlWindow : Window
{
    Button btnUpdate = null;
    public DynamicXamlWindow()
    {
        string s = XamlTemplate;

        // replace some things in the XamlTemplate here

        Window root = System.Windows.Markup.XamlReader.Load(...);
        Object _root = this.InitializeFromXaml(new StringReader(s).ReadToEnd()); //??

        btnUpdate = // ???

        //InitializeComponent();
    }

The XamlTemplate line looks like this:

    private string XamlTemplate = @"
    <Window x:Class='@@CLASS'
            xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation'
            xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'
            Title='@@TITLE' 
            Height='346' Width='380'>

        <Grid>
          ...

I saw examples where a button or section is defined in XAML and loaded dynamically. But this is not a button or section. XamlTemplate provides XAML for the actual window.

InitializeFromXaml XamlReader.Load? , ?

, XAML, btnUpdate . ?

+3
2

x: class. , , , :

private string XamlTemplate = @"
    <control:BaseWindow
            xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation'
            xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'
            xmlns:control='WhateverHere'
            Title='@@TITLE' 
            Height='346' Width='380'>
        <Grid>...

:

XamlReader.Parse(xaml);

, this.FindName( "btnUpdate" ) .

+4

. xaml, InitializeComponent. :

System.Uri resourceLocater = new System.Uri("/SampleWpfApp;component/window1.xaml", System.UriKind.Relative);
System.Windows.Application.LoadComponent(this, resourceLocater);

, System.Windows.Application.LoadComponent(windowInstance, uri);

+2

Source: https://habr.com/ru/post/1714729/


All Articles