簡單場景:this
列表綁定後臺數據,點擊列表項在view的cs中拿點擊項的DataContext進一步處理。正常狀況下應該是能拿到我綁定上去的數據,可是偶爾會點出來DisconnectedItem,重現概率不小,大概四五次就能點出一次。spa
<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應當是邏輯樹的一部分,在綁定斷開的時候的狀態,至於爲何會在正常狀態下點出來不得而知。blog
微軟表示在4.5中會修復這個bugit
由 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單憋死吧,只能各類瞎試,特麼還真試出個方法。io
<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的問題了。event
bug單是走了,可是還不明白內部的原理,不求甚解,呵呵。class