I have a problem with my data binding, probably a small one. I have tried to implement the MVVM pattern in my application. Therefore I have a model containig my data. This data gets updated over the network in a periodic way. On top of this model I have a view model to bind to. In this view model I have a ObservableCollection, which I want to bind. The problem I have is, that my view model needs to be a global resource. Thats why I use the following attempt in my NavigationWindow :
<NavigationWindow.DataContext>
<localvm:DataViewModel/>
</NavigationWindow.DataContext>
The reason I have to use it as a global variable is, that this view model starts my network business logic. Thats probably a bad way but I could’nt find a solution to this. Anyway
to diplay my data I have a Frame in my NavigationWindow defined like this:
<Frame Source="/Views/Pages/Page1_SystemOverview.xaml" VerticalAlignment="Stretch></Frame>
in this loaded page I have a ItemsControl to view the Collection:
<Page>
<Grid>
<Grid.Resources>
<localcnv:DebugHelperConverter x:Key="debugCNV"/>
</Grid.Resources>
<StackPanel>
<ItemsControl ItemsSource="{Binding Source=ListOfQuerys}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Vertical"></StackPanel>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<StackPanel>
<Button Content="{Binding RelativeSource={RelativeSource Mode=TemplatedParent}, Path=(ItemsControl.AlternationIndex)}"/>
</StackPanel>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</StackPanel>
</Grid>
So here is my problem: When I start my program The ItemsControl contains 18 elements with no content at all. It should contain only two elements, the output window shows me no binding errors, but when I change the ItemsSource to
"{Binding Path=ListOfQuerys}"
it says:
System.Windows.Data Information: 41 : BindingExpression path error: 'ListOfQuerys' property not found for 'object' because data item is null. This could happen because the data provider has not produced any data yet. BindingExpression:Path=ListOfQuerys; DataItem=null; target element is 'ItemsControl' (Name=''); target property is 'ItemsSource' (type 'IEnumerable')
What am I doing wrong? I thought, when I set the DataContext in a parent class, I can use it down the tree but somehow it won’t work, any Ideas?
Thanks!
The content of the
Frameelement is not part of visual / logical tree and hence will not persist the data context. You will have to set it explicitly.Hope this helps…