1

Here is what I would like to do:

public partial class PhrasesFrame : Frame
{
    public PhrasesFrameViewModel vm = new PhrasesFrameViewModel(this);

    public PhrasesFrame()
    {
        InitializeComponent();
    }

public class PhrasesFrameViewModel : ObservableProperty
{

    PhrasesFrame phrasesFrame;

    PhrasesFrameViewModel(PhrasesFrame phrasesFrame) {
        this.phrasesFrame = phrasesFrame;
    }

I want to give the new PhrasesFrameViewModel a reference to the class that created it.

However I get the message:

Keyword "this" is not available in the current context

Alan2
  • 23,493
  • 79
  • 256
  • 450

1 Answers1

3

Create the view model in the constructor in order to have access to this keyword in the correct context.

public partial class PhrasesFrame : Frame {
    public PhrasesFrameViewModel vm;

    public PhrasesFrame() {
        InitializeComponent();
        vm = new PhrasesFrameViewModel(this);
    }

    //...
}

This assumes that the view model has a publicly accessible constructor that accepts the passed argument.

public class PhrasesFrameViewModel : ObservableProperty {

    private readonly PhrasesFrame phrasesFrame;

    public PhrasesFrameViewModel(PhrasesFrame phrasesFrame) {
        this.phrasesFrame = phrasesFrame;
    }

    //...
}
Nkosi
  • 235,767
  • 35
  • 427
  • 472
  • I tried this but it gives me an error saying 'PhrasesFrameViewModel.PhrasesFrameViewModel(PhrasesFrame)' is inaccessible due to its protection level (CS0122) – Alan2 Dec 24 '17 at 04:10
  • @Alan2 does the view model have a publicly accessible constructor that accepts the passed argument? – Nkosi Dec 24 '17 at 04:11
  • I added the view model class code to the question now. I think you are correct. It was not public. When I made it public then it seemed to work. Can you tell me, is this the correct coding for the view model? – Alan2 Dec 24 '17 at 04:12
  • 1
    @Alan2 standard practice if there is no intention to change the field after initialization/assignment. If you have intentions of changing the field then so not make it read-only. Reference: https://stackoverflow.com/questions/277010/what-are-the-benefits-to-marking-a-field-as-readonly-in-c – Nkosi Dec 24 '17 at 04:20