Alan2
Alan2

Reputation: 24572

How can I access a property of a page in a ViewModel?

I have this code that creates a ViewModel for the page. However in the Viewmodel I want to access the property correctButtonPressed but it's not available.

How can I access this?

public partial class PhrasesFrame : Frame
{
    public int correctButtonPressed;
    public PhrasesFrameViewModel vm = new PhrasesFrameViewModel();
    public PhrasesFrame() {
        InitializeComponent();
    }

    private string abc()
    {
        var a = correctButtonPressed;
    }


}

public class PhrasesFrameViewModel : ObservableProperty
{
    private ICommand bButtonClickedCommand;
    public ICommand BButtonClickedCommand
    {
        get
        {
            return bButtonClickedCommand ??
                (bButtonClickedCommand = new Command(() =>
                {
                    // Next line gives an error "use expression body for accessors" "use expression body for properties.
                    correctButtonPressed = 123;
                }));
        }
    }

}

Upvotes: 1

Views: 102

Answers (1)

Nkosi
Nkosi

Reputation: 247088

Expose it as a property on the view model and have the view access it.

public partial class PhrasesFrame : Frame {

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

    private string abc() {           
        //View can access correctButtonPressed via the view model.
        var a = vm.correctButtonPressed;
    }
}

public class PhrasesFrameViewModel : ObservableProperty {
    public int correctButtonPressed;

    private ICommand bButtonClickedCommand;
    public ICommand BButtonClickedCommand {
        get {
            return bButtonClickedCommand ??
                (bButtonClickedCommand = new Command(() => {
                    correctButtonPressed = 123;
                }));
        }
    }    
}

Upvotes: 2

Related Questions