WPF杂难解 奇怪的DisconnectedItem

简单场景:

  列表绑定后台数据,点击列表项在view的cs中拿点击项的DataContext进一步处理。正常情况下应该是能拿到我绑定上去的数据,但是偶尔会点出来DisconnectedItem,重现几率不小,大概四五次就能点出一次。

<ItemsControl ItemsSource="{Binding Source}">
      <ItemsControl.ItemsPanel>
            <ItemsPanelTemplate>
                  <StackPanel Orientation="Horizontal"/>
            </ItemsPanelTemplate>
      </ItemsControl.ItemsPanel>
      <ItemsControl.ItemTemplate>
            <DataTemplate>
                 <Image Source="{Binding Path}" MouseLeftButtonUp="Image_OnMouseLeftButtonUp"></Image>
            </DataTemplate>
      </ItemsControl.ItemTemplate>
</ItemsControl>

搜索了一把,能找到的帮助很少,DisconnectedItem应当是逻辑树的一部分,在绑定断开的时候的状态,至于为什么会在正常状态下点出来不得而知。

微软表示在4.5中会修复这个bug

由 Microsoft 在 2011/7/7 16:51 发送
In the next release, we will not raise DataContextChanged when changing to {DisconnectedItem}. We are also providing a way to check for {DisconnectedItem}.
 
我是用的3.5,暂时没有升级计划,有人说4.5也有问题:
 
由 skst 在 2012/12/11 5:34 发送
This is marked as Closed and Fixed. What, exactly, was the fix? Is a DisconnectedItem no longer being passed to the DataContextChanged event? Is there a way to test if an object is a DisconnectedItem?

I'm seeing DisconnectedItem passed to the Loaded event in WPF 4.5, so it seems that this object is still being exposed.

办法找不到,但是bug单还是挂着,总不能被bug单憋死吧,只能各种瞎试,特么还真试出个方法。

<ItemsControl ItemsSource="{Binding Source}">
      <ItemsControl.ItemsPanel>
            <ItemsPanelTemplate>
                  <StackPanel Orientation="Horizontal"/>
            </ItemsPanelTemplate>
      </ItemsControl.ItemsPanel>
      <ItemsControl.ItemTemplate>
            <DataTemplate>
                 <Image DataContext="{Binding}" Source="{Binding Path}" MouseLeftButtonUp="Image_OnMouseLeftButtonUp"></Image>
            </DataTemplate>
      </ItemsControl.ItemTemplate>
</ItemsControl>

在DataTemplate上加一个强制绑定,再也没有重现过DisconnectedItem的问题了。

bug单是走了,但是还不明白内部的原理,不求甚解,呵呵。

posted @ 2013-07-24 11:09  shen6041  阅读(1263)  评论(0编辑  收藏  举报