2017-03-28 4 views
1

ComboBoxのItemsSourceは、ViewModel内の項目のリストにバインドされ、SelectedItemはプロパティにバインドされています。別のリストにバインドされている別のComboBoxもありますが、代わりにSelectedIndexが使用されます。最初のコンボボックスからアイテムを選択すると、コンボボックスの秒の内容が変更され、SelectedIndexにバインドされたプロパティは-1に設定され、コンボボックスでは何も選択されません。ComboBoxでSelectedIndexをリセットするキャリバー

なぜSelectedIndexプロパティが-1にリセットされていますか?それを防止するにはどうすればよいですか?

ビュー

<ComboBox ItemsSource="{Binding MyList}" SelectedItem="{Binding MySelectedItem}"></ComboBox> 
<ComboBox ItemsSource="{Binding MyArray}" SelectedIndex="{Binding MySelectedIndex}"></ComboBox> 

のViewModel

public List<Foo> MyList { get; set; } 
private Foo _mySelectedItem; 
public Foo MySelectedItem { 
    get { return _mySelectedItem; } 
    set { 
     if (Equals(value, _mySelectedItem)) return; 
     _mySelectedItem = value; 
     NotifyOfPropertyChange(); 
     MyArray = new [] { "othervalue1", "othervalue2", "othervalue3" }; 
     NotifyOfPropertychange(() => MyArray); 
    } 
} 
public string[] MyArray { get; set; } 
public int MySelectedIndex { get; set; } 

public MyViewModel() { 
    MyList = new List<Foo> { new Foo(), new Foo(), new Foo() }; 
    MySelectedItem = MyList.First(); 

    MyArray = new [] { "value1", "value2", "value3" }; 
    MySelectedIndex = 1; // "value2" 

    NotifyOfPropertyChange(() => MyList); 
} 

ですから、MYLISTにバインドされたコンボボックスから何かを選択すると、MyArrayという、新しい値を使用して構築されます。これにより、新しい配列に同じインデックスが存在していても、MySelectedIndexは突然値-1になります。

+0

@dymanoidを。今すぐ修正しました。それを指摘してくれてありがとう。 – GTHvidsten

答えて

2

プロパティが新しいアイテムのコレクションに設定されていると、選択したアイテムがクリアされるため、実際にはSelectedItemがリセットされます。

しかしItemsSourceが更新された後、あなたはそれを一時変数にインデックスを格納し、再割り当てすることができるはずです。タイプミスだった

public Foo MySelectedItem 
{ 
    get { return _mySelectedItem; } 
    set 
    { 
     if (Equals(value, _mySelectedItem)) return; 
     _mySelectedItem = value; 
     NotifyOfPropertyChange(); 
     int temp = MySelectedIndex; 
     MyArray = new[] { "othervalue1", "othervalue2", "othervalue3" }; 
     NotifyOfPropertychange(() => MyArray); 

     SelectedIndex = temp; 
     NotifyOfPropertychange(() => SelectedIndex); 
    } 
} 
+0

現在選択されているインデックスを維持して、コンボボックスを補充した後にそれを元に戻しても問題ありません。ありがとう:) – GTHvidsten

関連する問題