Danny Chou
Danny Chou

Reputation: 31

Xamarin MvvM contentview binding

I've developing an App with Xaramin.

In my solution I've created a ContentView.xaml, as a custom GUI control.

<?xml version="1.0" encoding="UTF-8"?>
<ContentView xmlns="http://xamarin.com/schemas/2014/forms"
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
    xmlns:local="clr-namespace:test2;assembly=test2"
    x:Class="test2.MyView">

    <ContentView.BindingContext>
        <local:MyViewModel MyValue="1"/>
    </ContentView.BindingContext>

    <StackLayout>
        <Label HorizontalOptions="CenterAndExpand" VerticalOptions="CenterAndExpand" Text="{Binding MyValue}"/>
    </StackLayout>

</ContentView>

I've created a ViewModel Class for this ContentView:

using System;
using System.ComponentModel;
using Xamarin.Forms;

namespace test2
{
    public class MyViewModel : INotifyPropertyChanged
    {
        int myValue;

        public MyViewModel()
        {
            Device.StartTimer (TimeSpan.FromSeconds (1), () => {

                this.MyValue++;
                return true;
            });
        }

        public int MyValue
        {
            set
            {
                if (! myValue.Equals(value)) {

                    myValue = value;
                    OnPropertyChanged ("myValue");
                }
            }
            get
            { 
                return myValue;
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;

        protected void OnPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null) {

                PropertyChanged (this, new PropertyChangedEventArgs (propertyName));
            }
        }
    }
}

I've also created a ContentPage.xaml, and added my custom control in it.

<?xml version="1.0" encoding="UTF-8"?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
    xmlns:local="clr-namespace:test2;assembly=test2"
    x:Class="test2.MyPage">

    <local:MyView />

</ContentPage>

I found the Label never update, why?

Upvotes: 3

Views: 4362

Answers (1)

ThumbGen
ThumbGen

Reputation: 172

At a first sight you should replace

OnPropertyChanged ("myValue");

with

OnPropertyChanged ("MyValue");

as the property name is case sensitive

Upvotes: 1

Related Questions