开发者

Trouble with deferred evaluation and DataGrid.ItemsSource

开发者 https://www.devze.com 2023-02-10 06:54 出处:网络
I am experiencing an issue setting the ItemsSource property of a DataGrid to the result of a LINQ query.The exact error is:

I am experiencing an issue setting the ItemsSource property of a DataGrid to the result of a LINQ query. The exact error is:

Cannot acce开发者_如何学编程ss a disposed object. Object name: 'DataContext accessed after Dispose.'.

Now, before you start snickering and whip off an answer regarding deferred query evaluation and disposing of your database contexts, know that I do understand all of that. I am calling ToList() on the result of the query and assigning that to the ItemsSource property. So, query executed, results read into memory, should be ok.

Yeah, not so much. At first I thought that there must be something about the property itself causing this, i.e., some weird data binding thing that I don't know about (learning WPF and linq2Sql at the moment). After thinking some more about it, I still couldn't explain the problem as the DataGrid shouldn't have any notion of the DataContext, just the list (though returning a List from a test method and iterating through it later did not throw an exception).

It was the DataContext that was being accessed after its destruction, but that doesn't help me understand either because I am calling ToList() specifically to execute the query before the using block exits. I can however solve the problem as shown below:

private void button1_Click( object sender, RoutedEventArgs e )
{
    using( NorthwindDataContext db = new NorthwindDataContext() )
    {
        db.DeferredLoadingEnabled = false;  // works, but why is it necessary at all?
        grid.ItemsSource = (from o in db.Orders
                            where o.CustomerID == "VINET"
                            select o).ToList();
    }
}

So yeah, I'd like to understand this behavior before moving on too far. Thanks in advance.

EDIT: xaml for the main window and DataGrid

<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="495" Width="722">
    <Grid>
        <DataGrid AutoGenerateColumns="true" Height="403" HorizontalAlignment="Left" Margin="12,41,0,0" Name="grid" VerticalAlignment="Top" Width="676" />
        <Button Content="Do it" Height="23" HorizontalAlignment="Left" Margin="12,12,0,0" Name="button1" VerticalAlignment="Top" Width="75" Click="button1_Click" />
    </Grid>
</Window>


Your code indicates that setting DeferredLoadingEnabled to false fixed this? If so I'd assume that your databinding was accessing properties of a related object, which, when accessed, was trying to fire off a new query to retrieve said object.

0

精彩评论

暂无评论...
验证码 换一张
取 消