SilverLight学習ノート1のComboBox


1,ComboBox単純バインド
 <ComboBox Grid.Row="1" Grid.Column="3"  Height="20" HorizontalAlignment="Left"  VerticalAlignment="Top" Name="lstSex" Width="100" Margin="5,4,0,0" SelectedIndex="0">
    <ComboBoxItem Content=" " />
    <ComboBoxItem Content=" " />
</ComboBox>

2,ComboBoxデータバインド
2.1 xmal
<ComboBox Grid.Row="0" Grid.Column="3" Height="20" HorizontalAlignment="Left"  VerticalAlignment="Top" Name="Comb1" Width="100" Margin="5,8,0,0">
</ComboBox>

2.2データソース
public class Student
{
    public string Name
    {
        set;
        get;
    }
}

public class Students
{
    public List<Student> StudentList
    {
        set;
        get;
    }
	
    public List<Student> getStudent()
    {
        StudentList= new List<Student>  
            {
                new Student(){Name="X1"},
                new Student(){Name="X2"},
                new Student(){Name="X3"}
            };
        return StudentList;
    }
}

2.2バックグラウンドコード
private void BindStudent()
{
    Comb1.ItemsSource = new Students().getStudent();
    Comb1.DisplayMemberPath = "Name";
}

3 ComboBox賦課
3.1 ComboBoxのItemsが固定されている状態
Comb1.ItemsSource = new Students().getStudent();
switch (userModel.UserDepartment )
{
    case "X1":
        this.Comb1 .SelectedIndex =0;
        break;
    case "X2":
        this.Comb1 .SelectedIndex =1;
        break;                    
    case "X3":
        this.Comb1 .SelectedIndex =2;
        break;                                    
}

3.2 ComboBoxのItemsが変化する場合
データベースにstudentをクエリーします.Name,Nameはいつでも変更される可能性があります
foreach(Student item in Comb1.Items)
{
    if(item.Name == student.Name)
     {
        Comb1.SelectedItem = item;
    }
}