2011-05-13 67 views
1

我的XAML ...的Silverlight 4 {}綁定通用字典到列表框中

<ListBox Margin="6,35,6,6" Name="lbLayers" SelectionMode="Extended" > 
    <ListBox.ItemTemplate> 
     <DataTemplate> 
      <StackPanel Orientation="Vertical"> 
       <TextBlock Text="{Binding Key,Mode=TwoWay}" /> 
       <TextBlock Text="{Binding Value.Visible,Mode=TwoWay,StringFormat='Visible: {0}'}" /> 
      </StackPanel> 
     </DataTemplate> 
    </ListBox.ItemTemplate> 
</ListBox> 

..和我的代碼是...

void GameEvents_MapCreated(object sender, Zider.EventArgs.MapEventArgs e) 
    { 
     HookMapLayerEvents(false); 
     this.map = e.Map; 
     HookMapLayerEvents(true); 
     this.lbLayers.ItemsSource = this.map.Layers; 
    } 

this.map。圖層是類型的通用字典(字符串,MapLayer(Tile))

當我在列表框中設置ItemSource時,字典中沒有任何項目可以啓動。當我點擊一個按鈕時,當我添加地圖圖層

this.map.Layers.Add("key", new MapLayer<Tile>()); 

此外MapLayer實現INotifyPropertyChanged爲它的屬性。

對於我的生活,我似乎無法獲得要顯示在列表框中的項目。

回答

2

問題是map.Layers的值不會改變,Dictionary<TKey, TValue>也不會執行INotifyCollectionChanged接口。因此,ListBox無法知道任何新項目可用於顯示。

如果可能,請嘗試更改Layers屬性,以便它代替公開ObservableCollection<T>

當然這可能是一個問題,如果你必須有一本字典。如果您只對確保唯一條目感興趣,則可以使用密鑰的HastSet來管理該條目。如果你需要查找密鑰,那麼如果有少量項目順序搜索應該做得相當好。

一個完整的解決方案可能是實現ObservableDictionary,該接口既有IDictionary<TKey, TValue>也有INotifyCollectionChanged接口。有幾個關於如果您搜索「ObservableDictionary Silverlight」,只是要小心,他們實際上實現了正確的接口,它不好,如果它的「可觀察」,但不符合與ItemsSource兼容。

+0

經過一些更多的搜索後,我遇到了這篇文章http://blogs.microsoft.co.il/blogs/shimmy/archive/2010/12/26/observabledictionary-lt-tkey-tvalue-gt-c.aspx我將ItemSource設置爲一個沒有實現INotifyCollectionChanged接口的集合。 – 2011-05-13 21:26:23

相關問題