Change the background color of a toggle button when the toggle button is checked

ControlTemplate triggers on ToggleButton

ControlTemplate.Triggers プロパティ (System.Windows.Controls)

[WPF] Templateでできることと書き方

WPF Styles and Triggers - WPF Controls

ボタンコントロール

トグルボタンを作成して「正常」と「異常」の表示を切り替え、色も緑と赤で切り替えるサンプルコードをPowerShellとXAMLで作成します。

プロジェクトフォルダの構成

📂ToggleButtonApp
┣ 📂GUI
┃ ┣ 📜MainWindow.xaml
┃ ┗ 📜MainWindow.ps1
┣ 📜App.ps1
┗ 📜App-Shortcut.ps1

MainWindow.xaml

<Window xmlns="<http://schemas.microsoft.com/winfx/2006/xaml/presentation>"
        xmlns:x="<http://schemas.microsoft.com/winfx/2006/xaml>"
        Title="Toggle Button Example" Height="200" Width="300">
    <Grid>
        <Button Name="ToggleButton" Content="正常" Background="Green"
                Foreground="White" Width="100" Height="50"
                HorizontalAlignment="Center" VerticalAlignment="Center"/>
    </Grid>
</Window>

MainWindow.ps1

Class MainWindow {
    [xml]$Xaml
    [System.Windows.Window]$Window
    [System.Windows.Controls.Button]$ToggleButton

    MainWindow() {
        $this.LoadXaml()
        $this.InitializeComponent()
    }

    [void]LoadXaml() {
        $XamlPath = Join-Path -Path (Split-Path -Path $MyInvocation.MyCommand.Definition -Parent) -ChildPath "MainWindow.xaml"
        $this.Xaml = [xml](Get-Content -Path $XamlPath)
    }

    [void]InitializeComponent() {
        $reader = (New-Object System.Xml.XmlNodeReader $this.Xaml)
        $this.Window = [Windows.Markup.XamlReader]::Load($reader)
        $this.ToggleButton = $this.Window.FindName("ToggleButton")

        $this.ToggleButton.Add_Click({ $this.OnToggleButtonClick($this.ToggleButton) })
    }

    [void]OnToggleButtonClick([System.Windows.Controls.Button]$button) {
        if ($button.Content -eq "正常") {
            $button.Content = "異常"
            $button.Background = [System.Windows.Media.Brushes]::Red
        } else {
            $button.Content = "正常"
            $button.Background = [System.Windows.Media.Brushes]::Green
        }
    }

    static [void]Show() {
        $window = [MainWindow]::new()
        $null = $window.Window.ShowDialog()
    }
}

App.ps1

Add-Type -AssemblyName PresentationFramework
Add-Type -AssemblyName PresentationCore
Add-Type -AssemblyName WindowsBase

Import-Module "$PSScriptRoot\\\\GUI\\\\MainWindow.ps1"

[MainWindow]::Show()

App-Shortcut.ps1

# このファイルはApp.ps1を起動するショートカットです
$scriptPath = Split-Path -Path $MyInvocation.MyCommand.Definition -Parent
& "$scriptPath\\\\App.ps1"

トグルボタンコントロール

トグルボタンコントロール(ToggleButton)を使用して「正常」と「異常」の表示および色を切り替える例を作成します。