Binding ComboBox.SelectedItem in Silverlight (more)

做~自己de王妃 提交于 2019-12-04 03:22:19

This is a bug in the ComboBox control that has to do with the changing pointer of the ItemsSource's binding. The solution that I have found is to:

1) Always bind the ItemsSource to an observable collection and never reset the pointer of the OC.

<ComboBox ItemsSource="{Binding MyList}" SelectedItem="{Binding MyItem}" />

Bad:

MyList = new ObservableCollection();

Good:

MyList.Clear();
MyList.AddRange(...);

2) Set MyItem = null, before Clearing MyList

In your case you are changing the reference of the List whenever you change CurrentView. Therefore, if SelectedItem is not null, there is a brief moment in time where the ItemsSource is being reset, the internals of the ComboBox are attempting to locate the SelectedItem object in the new ItemsSource but the old object is not there.

Thanks for the suggestions above. In my situation I am able to go for the "nuclear option", which is -- whenever the selected item needs to change, I completely destroy the ComboBox, make a new one, and set its SelectedItem appropriately.

Ridiculous, but it works.

Combobox is a quite buggy SL control :-(.

In my case I gave up with the selected item declarativa binding and use the nasty coding approach... ugly but works:

http://blogs.msdn.com/mikehillberg/archive/2009/03/26/implementing-selectedvalue-with-the-silverlight-combobox.aspx

HTH Braulio

I was getting the same issue a while ago and from what I can tell it's a bug in ComboBox when the ItemSource is changed it has an issue with the layout and scrolls badly.

There is a work around by calling ComboBox.UpdateLayout between setting the ItemSource and SelectedItem.

I blogged about the problem a while ago at Gotcha when databinding a ComboBox in Silverlight.

I've yet to verify whether the problem still exists in the Silverlight 3 Beta

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!