読者です 読者をやめる 読者になる 読者になる

「Androidは電気羊の夢を見るか」を読みたい管理者のブログ

仕事などでの色々な発見を記事にしてます。不定期更新。

コンボボックスの使い方

-その1

>>
        <ComboBox HorizontalAlignment="Left" Margin="44,83,0,0" VerticalAlignment="Top" Width="120">
            <ComboBoxItem>アイテム1</ComboBoxItem>
            <ComboBoxItem>アイテム2</ComboBoxItem>

        </ComboBox>
<<

 


-その2 ItemsSourceを指定
View

>>
        <ComboBox ItemsSource="{Binding items}"
                  DisplayMemberPath="Label"
                  SelectedValuePath="Ratio"
                  SelectedItem="{Binding Ratio}"
                      >
            <ComboBox.DataContext>
                <vm:ComboboxViewModel/>
            </ComboBox.DataContext>
        </ComboBox>
<<

 


ViewModel

>>
    class ComboboxViewModel
    {
        public List<Items> items{get;set;}
        public ComboboxViewModel()
        {


            items = new List<Items>();
            for(int i=0;i<10;i++)
            {
                items.Add(new Items(i,i.ToString()));
            }
        }

    }



    class Items
    {
        private float ratio;
        public float Ratio
        {
            get
            {
                return ratio;
            }
            set
            {
                ratio = value;
            }
        }

        private string label;

        public string Label
        {
            get{
                return label;
            }
            set
            {
                label = value;
            }
        }
        public Items(float ratio, string label)
        {
            this.ratio = ratio;
            this.label = label;
        }

    }
<<

 こういうことだってばよ

   <StackPanel>
        <ComboBox Width="88" HorizontalAlignment="Left" VerticalAlignment="Top" Name="com1">
            <ComboBoxItem></ComboBoxItem>
            <ComboBoxItem>iii</ComboBoxItem>
        </ComboBox>
        <ComboBox Width="88" HorizontalAlignment="Left" ItemsSource="{Binding items}"
                  DisplayMemberPath="Label"
                  SelectedValuePath="Ratio"
                  SelectedItem="{Binding Ratio}"
                  Name="com2"
                      >
            <ComboBox.DataContext>
                <vm:ComboboxViewModel/>
            </ComboBox.DataContext>
        </ComboBox>
        <TextBlock Text="{Binding ElementName=com1,Path=SelectedItem}"/>
        <TextBlock Text="{Binding ElementName=com2,Path=SelectedItem.Label}"/>

        <TextBlock Text="{Binding ElementName=com2,Path=SelectedValue}"/>



    </StackPanel>

 ViewModelは省略