2011-05-02 31 views
2

我正在試圖添加嵌入在XAML中的WPF代碼隱藏並使用powershell添加類型進行編譯。 有PowerBoots,但我不想使用它。我試圖嵌入的代碼是here。我提到The PowershellGuy way的實施,但仍然需要使用文件後面的代碼。使用添加類型的powershell編譯WPF Xaml而不使用PowerBoots

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 

從後面的鏈接代碼代碼是

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(); 
    } 

謝謝!

回答

1

您不能在XAML上通過XamlReader加載代碼隱藏,這基本上意味着您無法執行您想要執行的操作(在寬鬆XAML中覆蓋Window的OnRender方法),而無需創建從Window類派生的新類型...

但這是矯枉過正你想要做什麼,我想:

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 
1

我不知道是否有幫助,但這裏是一個例如,在按鈕「單擊」操作後面添加某種PowerShell代碼。

#requires -version 2 
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="300" Width="408"> 
    <Grid> 
     <Button x:Name="button1" 
       Width="75" 
       Height="23" 
       Canvas.Left="118" 
       Canvas.Top="10" 
       Content="Click Here" /> 
    </Grid> 
</Window> 
"@ 

Clear-Host 
$reader=(New-Object System.Xml.XmlNodeReader $xaml) 
$target=[Windows.Markup.XamlReader]::Load($reader) 
$control=$target.FindName("button1") 
$eventMethod=$control.add_click 
$eventMethod.Invoke({$target.Title="Hello $((Get-Date).ToString('G'))"}) 
$target.ShowDialog() | out-null 
+0

這聽起來不錯。我認爲嵌入不帶XAML的C#代碼比Xaml本身更可取。感謝JPBlanc和JayKul! – Deku 2011-05-03 20:54:23