我有一个ComboBox,其ItemsSource
绑定到我的ViewModel中的项目列表以及绑定到属性的SelectedItem
。我还有另一个绑定到另一个列表的ComboBox,但它使用SelectedIndex
代替。当我从第一个ComboBox中选择一个项目时,它会更改秒组合框的内容,并且绑定到SelectedIndex
的属性将设置为-1
,这将导致无法在组合框中选择任何内容。
为什么SelectedIndex
属性重置为-1,我该怎么做才能阻止它?
查看
<ComboBox ItemsSource="{Binding MyList}" SelectedItem="{Binding MySelectedItem}"></ComboBox>
<ComboBox ItemsSource="{Binding MyArray}" SelectedIndex="{Binding MySelectedIndex}"></ComboBox>
视图模型
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);
}
因此,从ComboBox中选择绑定到MyList的内容会导致MyArray使用新值构建。这导致MySelectedIndex突然具有值-1
,即使新数组中存在相同的索引。
答案 0 :(得分:2)
SelectedItem
确实已重置,因为当ItemsSource
属性设置为新的项目集合时,所选项目将被清除。
但您应该能够将索引存储在临时变量中,并在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);
}
}