I'm trying to make Avalon MVVM compatible in my WPF application. From googling, I found out that AvalonEdit is not MVVM friendly and I need to export the state of AvalonEdit by making a class derived from TextEditor then adding the necessary dependency properties. I'm afraid that I'm quite lost in Herr Grunwald's answer here:
If you really need to export the state of the editor using MVVM, then I suggest you create a class deriving from TextEditor which adds the necessary dependency properties and synchronizes them with the actual properties in AvalonEdit.
Does anyone have an example or have good suggestions on how to achieve this?
Herr Grunwald is talking about wrapping the
TextEditor
properties with dependency properties, so that you can bind to them. The basic idea is like this (using the CaretOffset property for example):Modified TextEditor class
Now that the
CaretOffset
has been wrapped in a DependencyProperty, you can bind it to a property, sayOffset
in your View Model. For illustration, bind aSlider
control's value to the same View Model propertyOffset
, and see that when you move the Slider, the Avalon editor's cursor position gets updated:Test XAML
Test Code-behind
Test View Model
You can use the Document property from the editor and bind it to a property of your ViewModel.
Here is the code for the view :
And the code for the ViewModel :
source : blog nawrem.reverse
Not sure if this fits your needs, but I found a way to access all the "important" components of the TextEditor on a ViewModel while having it displayed on a View, still exploring the possibilities though.
What I did was instead of instantiating the TextEditor on the View and then binding the many properties that I will need, I created a Content Control and bound its content to a TextEditor instance that I create in the ViewModel.
View:
ViewModel:
Test code in the ViewModel (works!)
At the moment I am still deciding exactly what I need my application to configure/do with the textEditor but from these tests it seems I can change any property from it while keeping a MVVM approach.