xlogI125’s blog

パソコン作業を効率化したい

XamlReader

Set-StrictMode -Version Latest

Add-Type -AssemblyName PresentationFramework

$xaml = @'
<Window Title="テスト" Width="600" Height="300" 
 xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
  <DockPanel>
    <TextBox AcceptsReturn="True" 
     HorizontalScrollBarVisibility="Visible" VerticalScrollBarVisibility="Visible" 
     FontFamily="MS ゴシック" FontSize="16">
      テキストを入力してください
    </TextBox>
  </DockPanel>
</Window>
'@

$window = [System.Windows.Markup.XamlReader]::Load(
  [System.Xml.XmlReader]::Create(
    [System.IO.StringReader]::new($xaml)
  )
) -as [System.Windows.Window]

$window.ShowDialog()
Set-StrictMode -Version Latest

Add-Type -AssemblyName PresentationFramework

$btn = New-Object -TypeName System.Windows.Controls.Button -Property @{
  Width   = 150
  Height  = 75
  Content = "クリックしてください"
}

$tBox = New-Object -TypeName System.Windows.Controls.TextBox -Property @{
  HorizontalScrollBarVisibility = [System.Windows.Controls.ScrollBarVisibility]::Visible
  VerticalScrollBarVisibility   = [System.Windows.Controls.ScrollBarVisibility]::Visible
  AcceptsReturn                 = $true
  FontFamily                    = [System.Windows.Media.FontFamily]::new("MS ゴシック")
  FontSize                      = 16
  Text                          = "テキストを入力してください"
}

$panel = [System.Windows.Controls.DockPanel]::new()
$panel.Children.Add($btn)
$panel.Children.Add($tBox)

$wnd = New-Object -TypeName System.Windows.Window -Property @{
  Width   = 600
  Height  = 300
  Title   = "テスト"
  Content = $panel
}

$hTextBoxTextChanged = [System.Windows.Controls.TextChangedEventHandler] {
  param([object]$s, [System.Windows.Controls.TextChangedEventArgs]$e)

  $btn.Content = "テキストが変更されました"
}

$hButtonClick = [System.Windows.RoutedEventHandler] {
  param([object]$s, [System.Windows.RoutedEventArgs]$e)

  $s.Content = "クリックされました"

  try {
    $xaml = $tBox.Text
    $stringReader = [System.IO.StringReader]::new($xaml)
    $xmlReader = [System.Xml.XmlReader]::Create($stringReader)
    $window = [System.Windows.Markup.XamlReader]::Load($xmlReader) -as [System.Windows.Window]
    $window.ShowDialog()
  }
  catch {
    $_ | Write-Verbose -Verbose
  }
}

$tBox.Text = [System.Windows.Markup.XamlWriter]::Save($wnd) -replace "><", ">`n<"

$tBox.add_TextChanged($hTextBoxTextChanged)
$btn.add_Click($hButtonClick)

$wnd.ShowDialog()