Change the background color of a toggle button when the toggle button is checked
ControlTemplate triggers on ToggleButton
ControlTemplate.Triggers プロパティ (System.Windows.Controls)
WPF Styles and Triggers - WPF Controls
トグルボタンを作成して「正常」と「異常」の表示を切り替え、色も緑と赤で切り替えるサンプルコードをPowerShellとXAMLで作成します。
📂ToggleButtonApp
┣ 📂GUI
┃ ┣ 📜MainWindow.xaml
┃ ┗ 📜MainWindow.ps1
┣ 📜App.ps1
┗ 📜App-Shortcut.ps1
<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>
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()
}
}
Add-Type -AssemblyName PresentationFramework
Add-Type -AssemblyName PresentationCore
Add-Type -AssemblyName WindowsBase
Import-Module "$PSScriptRoot\\\\GUI\\\\MainWindow.ps1"
[MainWindow]::Show()
# このファイルはApp.ps1を起動するショートカットです
$scriptPath = Split-Path -Path $MyInvocation.MyCommand.Definition -Parent
& "$scriptPath\\\\App.ps1"
トグルボタンコントロール(ToggleButton
)を使用して「正常」と「異常」の表示および色を切り替える例を作成します。