I have a small XAML form and i run it from within a powerShell script. It has a controltemplate called "newTab" which I use to create a tab with two buttons. Inside the XAML that works fine. But now I want to create a new tabItem inside the PowerShell code but missing the right syntax to achieve this. I was following this tutorial with is unfortunately in C#. The author did the trick like this:
// create new tab item
TabItem tab = new TabItem();
tab.Header = string.Format("Tab {0}", count);
tab.Name = string.Format("tab{0}", count);
tab.HeaderTemplate = tabDynamic.FindResource("TabHeader") as DataTemplate;
PowerShell script:
[xml]$XAML = @"
<Window
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
Title="MainWindow" SizeToContent="WidthAndHeight" MinWidth="250">
<Window.Resources>
<ControlTemplate x:Key="newTab" TargetType="TabItem" >
<StackPanel Orientation="Horizontal" >
<Button Content="Test1"/>
<Button Content="Test2"/>
</StackPanel>
</ControlTemplate>
</Window.Resources>
<Grid>
<Grid>
<TabControl Name="tabCon" TabStripPlacement="left" ItemsSource="{Binding}">
<TabItem Template="{StaticResource newTab}"/>
</TabControl>
</Grid>
</Grid>
</Window>
"@
$reader=(New-Object System.Xml.XmlNodeReader $xaml)
try{$Form=[Windows.Markup.XamlReader]::Load( $reader )}
catch{Write-Host "Unable to load Windows.Markup.XamlReader"; exit}
$xaml.SelectNodes("//*[@Name]") | ForEach-Object {Set-Variable -Name ($_.Name) -Value $Form.FindName($_.Name)}
#$myNewTab = New-Object PSObject -Property "NewTab"
#$tab = new-Object System.Windows.Controls.TabItem -Style "{StaticResource newTab}"
#$tabCon.AddChild($xaml.tryFindResource("newTab"))
$Form.ShowDialog() | out-null
CodePudding user response:
You can use FindResource
in PowerShell the same way you would in C#:
# Create new tab item
$tab = [System.Windows.Controls.TabItem]::new()
# Set template embedded in XAML form
$tab.Template = $Form.FindResource('newTab')