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
  • 1
  • 8

2 Answers2

3

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

private AboutViewModel viewmodel = new AboutViewModel();
PSK
  • 16,571
  • 4
  • 31
  • 42
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,817
  • 3
  • 27
  • 50