Error when updating DataContext for Windows Phone 7 Pivot
I'm trying to dynamically switch the DataContext
for my application when the selection of a Pivot
item changes. Everything works as I want it to, however I keep getting errors in the debugger output window about data sources not being found from the ListBoxes present inside the PivotItems that are not the currently selected PivotItem
.
For instance, let's say I have 2 PivotItems - PivotItem1 and PivotItem2 - each displaying one ListBox each - ListBox1 and ListBox2. Now, when PivotItem1 is active and displaying ListBox1, ListBox2 complains about its data source not being found, which is correct because the current DataContext
does not contain the collection it is bound to. This is the error (I've added extra line breaks):
System.Windows.Data Error: BindingExpression path error:
'Entries' property not found on 'MyApp.ViewModels.CategoriesView'
'MyApp.ViewModels.CategoriesView' (HashCode=79283607).
BindingExpression: Path='Entries'
DataItem='MyApp.ViewModels.CategoriesView'
(HashCode=79283607); target element is
'System.Windows.Controls.ListBox' (Name='ListBox2');
target property is 'ItemsSource' (type 'System.Collections.IEnumerable')..
Similarly, when PivotItem2 is active, ListBox1 throws an error. I'm updating the DataContext
within the LoadingPivotItem
event of the Pivot, I've also tried doing this within the LoadedPivotItem
event but get the same error.
Both collections implement INotifyPropertyChanged
, and as I mentioned at the beginning, everything works, despite the error. I'd like to suppress the error somehow.
Here's the XAML for one the ListBoxes:
<ListBox x:Name="ListBox1"
Margin="0,0,-12,0"
ItemsSource="{Binding Categories}">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Margin="0,0,0,17"
Width="432">
<TextBlock Text="{Binding CategoryName}"
TextWrapping="Wrap"
Margin="12,0,0,0"
Style开发者_如何学C="{StaticResource PhoneTextExtraLargeStyle}" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
The other is identical, except "Categories" is replaced by "Entries" and "CategoryName" by "EntryName".
Thanks in advance for your help.
While the action you're performing doesn't cause any errors in your application there will be an impact on the device as a whole while the Silverlight framework handles the binding errors.
Rather than having two different data models and changing them, why not have a single model which contains the "Categories" and "Entries" models but just set the one you're not displaying to be an empty collection (or whatever as appropriate). This would allow the bindings to still work but would prevent population of the list boxes you're not displaying.
精彩评论