2011-05-13 65 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

相关问题