1

私はこの問題に何時間も立ち往生しています...私がやりたいことは実際には非常に単純です-ComboBoxでデフォルトの選択されたアイテムを設定します(私はMVVMパターンを使用しています)。

ビューにComboBox用の次のXAMLがあります。

<ComboBox ItemsSource="{Binding Schools}" 
          DisplayMemberPath="Acronym" 
          SelectedValue="{Binding SelectedSchool}" 
          SelectedValuePath="Id" 
/>

私のViewModelには、ObservableCollection、Schoolsがあります。

 public ObservableCollection<School> Schools { get; private set; }

    public CourseFormViewModel()
    {
        Schools = new ObservableCollection<School>();

        try
        {
            // Gets schools from a web service and adds them to the Schools ObservableCollection
            PopulateSchools();
        }
        catch (Exception ex)
        {
            // ...
        }
    }

    public int SelectedSchool
    {
        get { return schoolId; }
        set
        {
            schoolId = value;
            OnPropertyChanged("SelectedSchool");
        }
    }

最後に、Schoolは単純なビジネスオブジェクトです。

[DataContract]
public class School
{
    [DataMember]
    public int Id { get; set; }
    [DataMember]
    public string Acronym { get; set; }
    [DataMember]
    public string Name { get; set; }
}

問題は、アプリケーションの起動時に、コンボボックスがデフォルト値を取得しないことです。XAMLでSelectedIndexを0に設定しようとしましたが、役に立ちませんでした。コードビハインドのWindow_LoadedイベントハンドラーでSelectedIndexを設定しようとしましたが(これは機能します)、MVVMパターンを使用しているため、ちょっと汚い感じがします。私はまだこのWPF/MVVM全体に慣れていないので、誰かが私を正しい方向に向けることができれば、私は感謝するでしょう。

4

1 に答える 1

5

SelectedSchoolは次のように設定できます。

public void CourseFormViewModel()
    {
        Schools = new ObservableCollection<School>();

        try
        {
            // Gets schools from a web service and adds them to the Schools ObservableCollection
            PopulateSchools();

            SelectedSchool = 3;
        }
        catch (Exception ex)
        {
            // ...
        }
    }

テストデータ:

 Schools.Add(new School { Id = 1, Name = "aaa", Acronym = "a" });
 Schools.Add(new School { Id = 2, Name = "bbb", Acronym = "b" });
 Schools.Add(new School { Id = 3, Name = "ccc", Acronym = "c" });

そして、あなたは選択されたアイテム「c」を手に入れるでしょう。

最小のIDでinitComboBoxが必要な場合は、次のコードを使用できます。

SelectedSchool = Schools.Min(x => x.Id);

定数値を割り当てる代わりに。

于 2012-12-09T20:17:13.780 に答える