在Silverlight中绑定ComboBox.SelectedItem(更多)

Jos*_*elo 8 data-binding silverlight combobox selecteditem

与我之前的问题相关:在Silverlight中绑定ComboBox.SelectedItem

我有一个像这样绑定的ComboBox:

<ComboBox x:Name="PART_CommentaryList" 
    HorizontalAlignment="Left" 
    Margin="3" 
    ItemsSource="{Binding Path=CurrentVideo.Commentaries}" 
    SelectedItem="{Binding Path=CurrentCommentary, Mode=TwoWay}">
Run Code Online (Sandbox Code Playgroud)

CurrentVideo和CurrentCommentary属性都会定期更改.几次后,我收到此错误:

Category: ManagedRuntimeError       
Message: System.ArgumentException: Value does not fall within the expected
   range.
   at MS.Internal.XcpImports.MethodEx(IntPtr ptr, String name, 
       CValue[] cvData)
   at MS.Internal.XcpImports.MethodPack(IntPtr objectPtr, String methodName, 
       Object[] rawData)
   at MS.Internal.XcpImports.UIElement_TransformToVisual(UIElement element, 
       UIElement visual)
   at System.Windows.UIElement.TransformToVisual(UIElement visual)
   at System.Windows.Controls.Primitives.Selector.IsOnCurrentPage(
       Int32 index, Rect& itemsHostRect, Rect& listBoxItemRect)
   at System.Windows.Controls.Primitives.Selector.ScrollIntoView(
       Int32 index)
   at System.Windows.Controls.Primitives.Selector.SetFocusedItem(
       Int32 index, Boolean scrollIntoView)
   at System.Windows.Controls.ComboBox.PrepareContainerForItemOverride(
       DependencyObject element, Object item)
   at System.Windows.Controls.ItemsControl.UpdateContainerForItem(
       Int32 index)
   at System.Windows.Controls.ItemsControl.RecreateVisualChildren()
   at System.Windows.Controls.ItemsControl.RecreateVisualChildren(
       IntPtr unmanagedObj)
Run Code Online (Sandbox Code Playgroud)

这对我来说似乎是一个ComboBox错误.我可以在CurrentCommentary之前验证CurrentVideo是否更改,因此所选项应始终是列表中的项.

相关,我真的不想要Mode = TwoWay,因为当ItemsSource被更改时,SelectedItem暂时为null,它在我的模型中被设置回来,我实际上并不想要.但是绑定根本不起作用(这似乎是另一个错误).

mar*_*kti 13

这是ComboBox控件中的一个错误,它与ItemsSource绑定的更改指针有关.我找到的解决方案是:

1)始终将ItemsSource绑定到可观察的集合,并且永远不会重置OC的指针.

<ComboBox ItemsSource="{Binding MyList}" SelectedItem="{Binding MyItem}" />
Run Code Online (Sandbox Code Playgroud)

坏:

MyList = new ObservableCollection();
Run Code Online (Sandbox Code Playgroud)

好:

MyList.Clear();
MyList.AddRange(...);
Run Code Online (Sandbox Code Playgroud)

2)在清除MyList之前设置MyItem = null

在您的情况下,只要更改CurrentView,就会更改List的引用.因此,如果SelectedItem不为null,则会重置ItemsSource的短暂时间,ComboBox的内部尝试在新的ItemsSource中找到SelectedItem对象,但旧对象不在那里.


Bra*_*lio 0

Combobox 是一个相当有缺陷的 SL 控件:-(。

就我而言,我放弃了所选项目声明绑定并使用令人讨厌的编码方法......丑陋但有效:

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

HTH 布劳略