icsharpcode / AvalonEdit

The WPF-based text editor component used in SharpDevelop
http://avalonedit.net/
MIT License
1.85k stars 471 forks source link

TextEditorOption throw “Object reference not set to an instance of an object” when VM is destructed #352

Open saderickhuang opened 2 years ago

saderickhuang commented 2 years ago

I'm working on a notepadplus-like editor with avalonEdit. I made a control class based on avalonedit and put it in a tab control template like this:

<TabControl Grid.Row="3"  ItemsSource="{Binding DocList}" SelectedItem="{Binding SelectedItem,Mode=TwoWay}" >
            <TabControl.ItemTemplate>
                <DataTemplate>
                </DataTemplate>
            </TabControl.ItemTemplate>
            <TabControl.ContentTemplate>
                <DataTemplate>
                    <Grid>
                        <Grid.Resources>
                            <avalonEdit:TextEditorOptions x:Key="TextEditOptions" />
                        </Grid.Resources>
                        <controls:TextEditorEx x:Name="avEditor"
                                Background="White"
                                Foreground="Black"
                                LineNumbersForeground="Black"
                                ShowLineNumbers="{Binding ShowLineNumbers, UpdateSourceTrigger=PropertyChanged}"
                                IsModified="{Binding Path=IsDirty, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
                                SyntaxHighlighting="{Binding HighlightingDefinition, Mode=OneWay, UpdateSourceTrigger=PropertyChanged}"
                                Document="{Binding Document, Mode=OneWay, UpdateSourceTrigger=PropertyChanged}"
                                Column="{Binding SynchronizedColumn,Mode=OneWayToSource, UpdateSourceTrigger=PropertyChanged}"
                                Line="{Binding SynchronizedLine,Mode=OneWayToSource, UpdateSourceTrigger=PropertyChanged}"
                                FontSize="{Binding SynchronizedFontSize, UpdateSourceTrigger=PropertyChanged}"
                                FontFamily="{Binding SynchronizedFontFamily, UpdateSourceTrigger=PropertyChanged}"
                                Options="{Binding TextEditorOptionsSetting, FallbackValue={StaticResource TextEditOptions}}"
                                >
                        </controls:TextEditorEx>
                    </Grid>
                </DataTemplate>
            </TabControl.ContentTemplate>
        </TabControl>

and DocList is a list of viewmodel for controls:TextEditorEx, when click close btn of tab , certain vm will be removed from DocList. it works fine until i bind Options to VM,when VM is removed from DocList, it triggers OptionsChanged Event and throws “Object reference not set to an instance of an object”.

I'm new to MVVM and WPF so how can I fix this problem? It seems to me the View Model should be destruct AFTER control does.