如何在ViewModel中访问页面的属性?

时间:2017-12-24 03:20:59

标签: xamarin xamarin.forms

我有这个代码为页面创建一个ViewModel。但是在Viewmodel中我想访问属性correctButtonPressed但它不可用。

我如何访问它?

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;
                }));
        }
    }

}

1 个答案:

答案 0 :(得分:2)

将其作为视图模型上的属性公开,并让视图访问它。

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;
                }));
        }
    }    
}