WP7 Custom Class UI Binding Issue
I have a map with a MapItemsControl in my WP7 app that contains pushpins bound to items in a collection of custom classes. The pushpins are bound to properties of the item in the collection via a DataTemplate.
When an item is added to or removed from the collection, all pins display correctly, with properties as per bindings, but when just an items’ properties are modified, the UI does not update. The bindings just seem to get values from the source item upon loading, but I'd like them to keep the UI elements updated when the source collection items' properties are updated.
To illustrate, I’ll create a similar example:
Here’s a custom class:
Public Class Box
Property CurrentColor As Color
Property Location As GeoCoordinate
End Class
There's a collection of them:
Dim TempBoxes As ObservableCollection(Of Box)
My map control has a MapItemsControl in it:
<maps:MapItemsControl Name="BoxControl"
ItemTemplate="{StaticResource BoxTemplate}"
ItemsSource="{Binding TempBoxes}"/>
The item template is something like this:
<DataTemplate x:Key="BoxTemplate">
<maps:Pushpin Location="{Binding Location}" ManipulationStarted="BoxTouched">
<maps:Pushpin.Template>
<ControlTemplate>
<Ellipse Width="35" Height="35" Margin="54,148,366,584"
Stretch="Fill" StrokeThickness="4" Stroke="Black"
Fill="{Binding CurrentColor}" />
</ControlTemplate>
</maps:Pushpin.Template>
</maps:Pushpin>
</DataTemplate>
The touch event handler switches the pin's color between blue and red:
Private Sub BoxTouched(ByVal sender As Object, ByVal e As RoutedEventArgs)
With DirectCast(DirectCast(sender, Pushpin).DataContext, Box)
If .CurrentColor = Colors.Re开发者_如何学Cd Then
.CurrentColor = Colors.Blue
Else
.CurrentColor = Colors.Red
End If
End With
End Sub
Whenever I add or remove items from TempBoxes, the pins all render as they should (e.g. if I specify a color in the collection item, the pin shows the color).
Tapping on the item triggers the BoxTouched sub, which causes the item's color to change in the collection, but the UI doesn't change (pin color stays the same).
To get the UI to update the color, I have to get it to render the pins again, by adding something like this to BoxTouched:
BoxControl.ItemsSource = Nothing
BoxControl.ItemsSource = TempBoxes
I'm assuming there's a better way to do this?
In order for the DataTemplate
to respond to changes in property values for your data object you need to implement the INotifyPropertyChanged
interface on your data object so that property change notification is raised when your properties change.
Take a look at the VB samples in the MSDN documentation if you're unsure how to do this.
精彩评论