Caliburn 重置 ComboBox 上的 SelectedIndex

Caliburn resetting SelectedIndex on ComboBox

我有一个 ComboBox,它 ItemsSource 绑定到我的 ViewModel 中的项目列表,SelectedItem 绑定到 属性。我还有另一个 ComboBox 绑定到另一个列表,但它使用 SelectedIndex 代替。当我 select 来自第一个 ComboBox 的项目时,它会更改第二个 ComboBox 的内容,并且绑定到 SelectedIndex 的 属性 设置为 -1,这不会导致任何结果在 ComboBox 中 selected。

为什么 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);
}

因此,select将 ComboBox 中的内容绑定到 MyList 会导致使用新值构建 MyArray。这会导致 MySelectedIndex 突然具有值 -1,即使新数组中存在相同的索引。

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);
    }
}