WPFでコンポボックスを扱う際、ハードルが高く分からなかった為、やり方を教えてもらった。
その際の備忘録
やりたかったこと
・Binding を使ったコンポボックス
環境
・Visual studio 2019
・.NET Framwork 4.8
過程
public class ComboBoxDictionaries
{
// ComboBoxの一覧に表示するデータ
public Dictionary<int, string> HohgehogeTypeDictionary { get; }
= new Dictionary<int, string>();
public ComboBoxDictionaries()
{
// 列挙値とその表示文字列のDictionaryを作る
HohgehogeTypeDictionary .Add(700, "朝");
HohgehogeTypeDictionary .Add(1200, "昼");
HohgehogeTypeDictionary .Add(2000, "夜");
}
}
まず、コンポボックスのリストを参照するComboBoxDictionariesクラスを作成する。
このクラスは、コンポボックスで指定した値などを読み出す際にも使用するため、Enums.csファイルなどに作ると良いかも
public Dictionary<int, string> HohgehogeTypeDictionary { get; }
= new Dictionary<int, string>();
コンポボックスが読み取る為のプロパティを作成する。
<int, String>は、左は処理で使用し(Kye)、**右はコンポボックスで表示させる(Value)**型になる。
public ComboBoxDictionaries()
{
// 列挙値とその表示文字列のDictionaryを作る
HohgehogeTypeDictionary.Add(700, "朝");
HohgehogeTypeDictionary.Add(1200, "昼");
HohgehogeTypeDictionary.Add(2000, "夜");
}
「HohgehogeTypeDictionary」のリストの中身となる部分。
コンストラクタによって格納されている。
2.XAML側の表示
全体のコード
<Window x:Class="test.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:test"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Window.Resources>
<local:ComboBoxDictionaries x:Key="comboBoxDictionaries"/>
</Window.Resources>
<Grid>
<ComboBox Width="100" Height="20"
HorizontalAlignment="Center"
Margin="0,0,50,0"
ItemsSource="{Binding HohgehogeTypeDictionary,Source={StaticResource comboBoxDictionaries}}"
DisplayMemberPath="Value"
SelectedValue="{Binding Time}"
SelectedValuePath="Key"/>
</Grid>
</Window>
<Window.Resources>
<local:ComboBoxDictionaries x:Key="comboBoxDictionaries"/>
</Window.Resources>
Window.Resourcesで参照する辞書ComboBoxDictionariesを指定する。
ItemsSource="{Binding HohgehogeTypeDictionary,Source={StaticResource comboBoxDictionaries}}"
DisplayMemberPath="Value"
ItemSouceにBindingさせるリスト名を指定し、カンマで区切りリスト元のソース(指定した辞書のx:keyの値)を記載。
DisplayMemberPathに表示させる文字Valueを指定する。
これで、コンポボックスにHohgehogeTypeDictionary に指定した文字が表示されるようになる。
SelectedValue="{Binding Time}"
SelectedValuePath="Key"/>
**{Binding this.Time}**にコンポボックスの結果を持たせる変数などを結びつける。
**SelectedValuePath="Key"**でHohgehogeTypeDictionaryの左側の値を使用するようにする。