微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

与我之前的问题相关: Binding ComboBox.SelectedItem in Silverlight

我有一个像这样绑定的ComboBox

<ComboBox x:Name="PART_CommentaryList" 
    HorizontalAlignment="Left" 
    Margin="3" 
    ItemsSource="{Binding Path=CurrentVideo.Commentaries}" 
    SelectedItem="{Binding Path=CurrentCommentary,Mode=TwoWay}">

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)

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

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

解决方法

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

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

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

坏:

MyList = new ObservableCollection();

好:

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

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

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐