Why the DataContext returns null value for the out of the ListView Items?

Viewed 370

I have try to display the combobox Items inside the ListViewItems Template by using the below code snippets.And i am try to getting the datacontext of the combobx in combobox loaded event. And datacontext is returns the value only for viewed listViewItems. And it returns the null value for out of the listview items combobox.

<ListView ItemsSource="{Binding PersonsTest, Mode=OneWay}" x:Name="TieLines">
<ListView.ItemTemplate>
    <DataTemplate>
        <StackPanel>
            <ComboBox DataContext="{Binding Orders}" ItemsSource="{Binding Numbers}" Loaded="ComboBox_Loaded" Width="250" />
        </StackPanel>
    </DataTemplate>
</ListView.ItemTemplate>

Questions Why is return the DataContext value as null for out of the view Items in the ListView? How can get the data-context of out of the view ListViewItems? Or else if i need to enable any other properties to Binding the ComboBox DataContext in XAML level?

1 Answers

Just from the names of the data-bound properties it is very likely that you are using the binding incorrectly. When you bind PersonsTest to ItemsSource of ListView, it means that for each person in the PersonsTest collection the control takes the ItemTemplate and populates it as if the DataContext of the template was the specific person. Let's say we are currently instantiating the template for person P.

Now when you are using {Binding Orders} you are essentially using p.Orders property. However, when you set the DataContext of the ComboBox to p.Orders, now the following binding {Binding Numbers} becomes relative to p.Orders as well. So {Binding Numbers} basically means {Binding p.Orders.Numbers}. I presume this is not what you want, as I would be surprised if the Orders would have a property named Numbers.

I would expect that you would bind ComboBox.ItemsSource to Orders and then a ComboBox.ItemTemplate and customize it in turn instead of setting the DataContext, but as I don't know what your data model is, I am only guessing. The key is that you probably don't need to set the ComboBox.DataContext at all and instead just have to correctly set the ItemsSource property.

Related