[WinUI 3][DropDownButton] アイテムがクリックされたことを検知する

スポンサーリンク

この記事では DropDownButton でアイテムが検知されたことを知る方法について説明をします。

環境

開発環境 Microsoft Visual Studio Enterprise 2019
Version 16.11.5
Framework Microsoft .NET Framewohttps://blog.hiros-dot.net/?p=11007rk Version 4.8.04161

アイテムがクリックされたことを検知する

DropDownButton のアイテムがクリックされたことを検知するには、Click イベントを使用します。

以下は、DropDownItem のそれぞれのアイテム(MenuFlyoutItem)の tag プロパティに、ボタンの意味を表す文字列を設定しておき、Click イベントの中で tag の文字列を確認するようにしています。これにより、どのアイテムがクリックされたのかを検知することができます。

XAML の例

<Window
    x:Class="WinUISample.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:WinUISample"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d">

    <StackPanel Orientation="Vertical" HorizontalAlignment="Center">
        <TextBlock x:Name="myTextBlock" />
        <DropDownButton ToolTipService.ToolTip="Alignment">
            <TextBlock FontSize="14" Text="Alignment"/>
            <DropDownButton.Flyout>
                <MenuFlyout Placement="BottomEdgeAlignedLeft">
                    <MenuFlyoutItem Text="Left" Icon="AlignLeft" Tag="left"
                            Click="AlignmentMenuFlyoutItem_Click"/>
                    <MenuFlyoutItem Text="Center" Icon="AlignCenter" Tag="center"
                            Click="AlignmentMenuFlyoutItem_Click"/>
                    <MenuFlyoutItem Text="Right" Icon="AlignRight" Tag="right"
                            Click="AlignmentMenuFlyoutItem_Click"/>
                </MenuFlyout>
            </DropDownButton.Flyout>
        </DropDownButton>
    </StackPanel>
</Window>

C#の例

private void AlignmentMenuFlyoutItem_Click(object sender, RoutedEventArgs e)
{
    var tag = ((MenuFlyoutItem)sender).Tag.ToString();
    var msg = string.Empty;

    switch (tag)
    {
        case "left":
            msg = "Left";
            break;
        case "center":
            msg = "Center";
            break;
        case "right":
            msg = "right";
            break;
    }
            
    myTextBlock.Text = msg;
}
アイテムが選択されたことを検知する例

アイテムが選択されたことを検知する例

WinUi Tips

本サイトでまとめている WinUI Tips の一覧はこちらから確認できます。

Please follow and like us:

コメント

タイトルとURLをコピーしました