---
# System prepended metadata

title: UWP で Combobox を使用する 2021-06-14
tags: [UWP, Combobox]

---

---
lang: ja-jp
breaks: true
---
# UWP で Combobox を使用する 2021-06-14

## MainPage.xaml
```xml=
        <ComboBox
            ItemsSource="{x:Bind LstSetting, Mode=OneWay}"
            SelectedValue="{x:Bind CurrentSetting, Mode=TwoWay}" />
```

## MainPage.xaml.cs

```csharp=
    public sealed partial class MainPage : Page, INotifyPropertyChanged
    {
        private ObservableCollection<string> m_lstCombobox = new ObservableCollection<string>();

        public ObservableCollection<string> LstSetting
        {
            get
            {
                return m_lstCombobox;
            }
            //set { this.m_lstCombobox = value; }
        }

        private string m_selectedValue = "";
        public string CurrentSetting
        {
            get { return this.m_selectedValue; }
            set
            {
                if (Set(ref this.m_selectedValue, value))
                {
                }
            }
        }


        public MainPage()
        {
            this.InitializeComponent();
            this.DataContext = null;
        }

        private void Page_Loaded(object sender, RoutedEventArgs e)
        {
            m_lstCombobox.Clear();
            m_lstCombobox.Add("");
            m_lstCombobox.Add("選択肢２");
            m_lstCombobox.Add("選択肢３");
            CurrentSetting = "選択肢２";
        }

        public event PropertyChangedEventHandler PropertyChanged;

        private bool Set<T>(ref T storage, T value, [CallerMemberName] string propertyName = null)
        {
            if (Equals(storage, value))
            {
                return false;
            }

            storage = value;
            OnPropertyChanged(propertyName);
            return true;
        }

        private void OnPropertyChanged(string propertyName) => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));

    }
```

:::warning
```=
this.DataContext = this
```
のように設定すると、値が空文字の項目を選択するとクラス名が表示されてしまう。なぜだ？？
![](https://i.imgur.com/mTiDS4X.png)

:::

###### tags: `UWP` `Combobox`
