1

i don't know why my viewmodel is null when the One_Clicked is called, what am i missing in the viewmodel. i've tried debugging it when found that the Unknown Identifier is on the DisplayLabel property.

This is my ViewModel:

public class AboutViewModel : BaseViewModel
{
    public AboutViewModel()
    {
        Title = "About";
    }

    string displayLabel = "0";
    public string DisPlayLabel
    {
        get { return displayLabel; }
        set { SetProperty(ref displayLabel, value); }
    }

    public void ButtonOne()
    {
        DisPlayLabel = "1";
    }
}

Here is the Code behind where viewmodel get called:

public partial class AboutPage : ContentPage
{
    private AboutViewModel viewmodel;

    void Clear_Clicked(object sender, EventArgs e)
    {
    }

    void One_Clicked(object sender, EventArgs e)
    {
        if (viewmodel != null)
        {
            viewmodel.ButtonOne();
        }
    }

    public AboutPage()
    {
        InitializeComponent();
    }
}
dnn284
  • 53
  • 2
  • 9

2 Answers2

2

You need to create an instance of viewmodel before using it, like following.

private AboutViewModel viewmodel = new AboutViewModel();
PSK
  • 17,547
  • 5
  • 32
  • 43
1
private AboutViewModel viewmodel;

This is not going to magically initialize itself.

Either you do it in the .xaml.cs file:

private AboutViewModel viewmodel = new AboutViewModel();

or you do it directly in xaml via DataTemplate. You can see an example here.

Blacktempel
  • 3,935
  • 3
  • 29
  • 53