2021.1.7

ポップアップ(Popup)の黒の背景色を透過に設定する

ポップアップ(Popup)を使用する場合、デフォルトのままでは背景色が黒色で表示されてしまいます。ポップアップに余白などを設定する際は透過で表示されてほしいので、その方法についてになります。

コード

ポップアップの背景色を透過にするには、コントロールに「AllowsTransparency="True"」を設定します。

◆MainWindow.xaml


<Window x:Class="WpfApp1.MainWindow"
        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"
        xmlns:local="clr-namespace:WpfApp1"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="600">
    <Canvas>
        <TextBox Name="TextBox01" Canvas.Top="5" Canvas.Left="5" Width="150" Height="20"/>
        <Button Name="Button01" Canvas.Top="4" Canvas.Left="170" Content="選択" Padding="10, 2" Click="Button01_Click"/>
        <Popup Name="Popup01"
               PlacementTarget="{Binding ElementName=TextBox01}" Placement="Bottom" 
               StaysOpen="False" AllowsTransparency="True">
               <Canvas Width="220" Height="100">
               <Canvas Width="220" Height="80" Canvas.Top="20" Background="LightBlue">
                    <TextBlock Name="myPopupText">あいうえお</TextBlock>
                </Canvas>
            </Canvas>
        </Popup>
    </Canvas>
</Window>

◆MainWindow.cs


using System;
using System.Windows;

namespace WpfApp1
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void Button01_Click(object sender, EventArgs e)
        {
            Popup01.IsOpen = true;
        }
    }
}

実行結果

AllowsTransparencyを指定しない、または「false」とした場合、以下のように表示されますが、

「true」に設定すると、透過で表示されるようになります。

WPF】関連記事