A first chance exception of type 'System.InvalidOperationException' occurred in PresentationFramework.dll

17,108

Solution 1

Okay. Changing Visual Studio's debugger to stop at all exceptions lead me to some insite. The exception was "NewItemPlaceHolder is not allowed during an AddNew...", which occured because of a PropertyChanged event on my Entity. Turns out this exception was already being handled, so I think I'm good.

Solution 2

I'm going to take a wild guess since not all the details are present (update code, stack trace, etc) that you are changing the bound collection in a non-ui thread.

In which case, you need:

(in update logic)

Application.Current.Dispatcher.Invoke((Action)(() =>
    {
       // update collection here
    });
Share:
17,108
William
Author by

William

Updated on June 05, 2022

Comments

  • William
    William almost 2 years

    All,

    I'm using DataBase First Entity Framework v4.4. In the DB (and data model) is Table1 that has a 1:many relationship to Table2.

    I am binding a DataGrid in WPF to Table1.Local.First().Table2 (for simplicity, assume that there is an entity in Table1.Local to begin with).

    ViewModel:

    Public SomeEntityDBContextWithTable1AndTable2 Container { get; set; }
    Public ICollection Table2ToDisplay { get { return Container.Table1.Local.First().Table2; } } //Note: :Many navigation properties return ICollection<T>, but the object type is of ObservableCollection<T>.
    

    In XAML, I have the following

    <GroupBox Header=Table2 DataContext="{Binding Path=Table2ToDisplay, UpdateSourceTrigger=PropertyChanged}">
        <DataGrid ItemsSource="{Binding}" AutoGenerateColumns="False" CanUserAddRows="True">
            <DataGrid.Columns>
                <!--A bunch of columns-->
            </DataGrid.Columns>
        </DataGrid>
    </GroupBox>
    

    When clicking inside a NewItemPlaceHolder that happens to be a text box, I get the System.InvalidOperationException occuring in PresentationFramework.dll. This doesn't crash my application, but I see it in the Output. My guess is that entities are added on another thread, and thus CollectionChanged event fires on another thread, and this causes the InvalidOperationException. However, since the code is mainly done via XML, I can't seem to find a way to handle this exception (or is it already being handled, it's just that it is being reported to Output). Is there a safe way to use CanUserAddRows="True" with EntityFramework where ":Many" navigation properties are of type ObservableCollection?

    I should point out that I have also tried wrapping my Table2ToDisplay property inside a CollectionViewSource, but I still see the InvalidOperationException in the output.

    Thanks in advance.