👋

UWP環境でのComboBoxのBinding

2024/01/25に公開

はじめに

表題の実装で当初悩んだので、メモ

したいこと

comboBox自体は、項目を選択できるコントロールですが、これをBindingして使用したい。

概略の説明

登場するクラスは、こんな感じ

これらをBindして使用したい。

実装

プロジェクトの作成

まずは、VisualStudioを起動して、「新しいプロジェクトの作成」を選択。
作成するプロジェクトはUWPとしたいので、検索欄に「UWP」を入力して、「空白のアプリ(ユニバーサルWindows)」を選択して下さい。

クラスの作成

クラスをどんどん作成していきます。
ソリューションエクスプローラ上で、プロジェクトを右クリックして、「追加」「クラス」で追加してください。

selectEnum.cs

namespace App1
{
    public enum selectEnum
    {
        select01,
        select02,
        select03
            
    }
}

selectItem.cs

namespace App1
{
    public class selectItem : BindableBase
    {
        private selectEnum _enumValue;
        public selectEnum EnumValue
        {
            get => _enumValue;
            set => SetProperty(ref _enumValue, value);
        }
    }
}

selectItemList.cs

using System.Collections.Generic;

namespace App1
{
    public class selectItemList
    {
        public Dictionary<selectEnum, string> SampleEnumNameDictionary { get; } = new Dictionary<selectEnum, string>();

        public selectItemList() {
            SampleEnumNameDictionary.Add(selectEnum.select01, "項目1");
            SampleEnumNameDictionary.Add(selectEnum.select02, "項目2");
            SampleEnumNameDictionary.Add(selectEnum.select03, "項目3");
        }
    }
}

XAMLファイルの作成

今回はComboBoxの使い方なので、使用するコントロールはComboBoxを1個だけ
上記で作成したクラスを使用したいので、Page.Resourcesに登録して、x:keyで別名を付ける。この別名で、ComboBoxタグ内でBindingを行う。

プロパティ名 説明
ItemsSource 表示される項目リストを指定する。Dictionary型
DisplayMemberPath ItemsSourceで指定したDictionary型のKey/Valueのどちらをリスト項目とするかを選択
SelectedValuePath ItemsSourceで指定したDictionary型のKey/Valueのどちらを内部で使用する値とするかを選択
<Page
    x:Class="App1.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:App1"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
    <Page.Resources>
        <local:selectItem x:Key="selectItemData"/>
        <local:selectItemList x:Key="selectItemListData"/>
    </Page.Resources>
    <Grid >
        <ComboBox ItemsSource="{Binding SampleEnumNameDictionary,Source={StaticResource selectItemListData}}"
                  DisplayMemberPath="Value"
                  SelectedValue="{Binding EnumValue,Source={StaticResource selectItemData},Mode=TwoWay}"
                  SelectedValuePath="Key" />
    </Grid>
</Page>

Discussion