wpfxamlpowershellinlineadd-type

Compile WPF Xaml using Add-type of powershell without using PowerBoots


I was tying to add WPF code-behind embedded in the XAML and compile using the powershell add-type. There is PowerBoots but i don't want to use that. The code i am trying to Embed is here . I referred to The PowershellGuy way of implementation but still i need to use the code behind file.

Add-Type -AssemblyName presentationframework
[xml]$xaml = @' 
<Window 
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
Title="Window1"  Height="350" Width="525" AllowsTransparency="True"  
WindowStyle="None" 
WindowState="Maximized" Topmost="False"  IsHitTestVisible="False">
</Window> 
'@ 

$reader=(New-Object Xml.XmlNodeReader $xaml) 
$Form=[Windows.Markup.XamlReader]::Load( $reader ) 
$Form.ShowDialog() | out-null

The code behind code from the link is

protected override void OnRender(DrawingContext drawingContext)
{ 
   base.OnRender(drawingContext); 
   var screenGeometry = new RectangleGeometry(new Rect(0, 0, ActualWidth,   ActualHeight)); 
   var excludeRectangle = new RectangleGeometry(new Rect(200, 200, 150, 150)); 
   drawingContext.PushClip(CombinedGeometry.Combine(screenGeometry, excludeRectangle, GeometryCombineMode.Exclude, null)); 
   drawingContext.PushOpacity(.8);
   drawingContext.DrawRectangle(Brushes.Black, null, new Rect(0, 0, ActualWidth, ActualHeight));
   drawingContext.Pop(); drawingContext.Pop(); 
    } 

Thanks!


Solution

  • You can't have code-behind on XAML that's loaded via a XamlReader, which basically means that you can't do what you're trying to do (override the OnRender method of the Window in loose XAML) without creating a new type derived from the Window class ...

    But that's overkill for what you're trying to do, I think:

    Add-Type -AssemblyName presentationframework
    [xml]$xaml = @' 
    <Window 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    AllowsTransparency="True" WindowStyle="None" 
    Background="#AA000000" WindowState="Maximized" 
    Height="{x:Static SystemParameters.PrimaryScreenHeight}"
    Width="{x:Static SystemParameters.PrimaryScreenWidth}" 
    Title="Window Title" Topmost="False"  IsHitTestVisible="False"></Window> 
    '@ 
    
    $reader=(New-Object Xml.XmlNodeReader $xaml) 
    $Form=[Windows.Markup.XamlReader]::Load( $reader ) 
    $Form.ShowDialog() | out-null