Search code examples
c#data-bindingwindows-phone-7inotifypropertychanged

INotifyPropertyChanged implementation, binding does not work


I'm learning to create an app for WP7 (Mango), and somehow having this problem. This is not actual code to my app, but a simplified version of the same problem. I think mostly it's due to lack of deep understanding of how binding works.

XAML.

<TextBlock x:Name="PageTitle" Text="{Binding Title}" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}"/>

Code Behind.

private MainPageViewModel viewModel;

    // Constructor
    public MainPage()
    {
        InitializeComponent();
        this.Loaded += new RoutedEventHandler(MainPage_Loaded);
    }

    void MainPage_Loaded(object sender, RoutedEventArgs e)
    {
        viewModel = new MainPageViewModel();
        this.DataContext = viewModel;
    }

    private void ApplicationBarIconButton_Click(object sender, EventArgs e)
    {
        viewModel.GenerateTitle();
    }

And my ViewModel.

        private static int counter = 0;

    private string title;
    public string Title
    {
        get { return title; }
        set
        {
            if (title != value)
            {
                title = value;
                OnPropertyChanged("Title");
            }
        }
    }

    public MainPageViewModel()
    {
        title = "Init";
    }

    public void GenerateTitle()
    {
        if (counter == 0)
            title = "0"; // Title = "0" will work fine.
        if (counter == 1)
            title = "1";

        counter++;
    }

Problem is, it only update the binding once inside my ViewModel constructor, so the title is "Init".

Any call to the GenerateTitle does not update the property. It works if I use 'Title' instead of 'title', which calls the setter.

Or I should really use 'Title'? I haven't done much C#, so my understanding of OOP is not that great yet.


Solution

  • The following line in the setter is what notifies the observers that he value has changed:

    OnPropertyChanged("Title");
    

    When you use the private field value, that method isn't being called so the observers aren't being notified that the value of the property has changed.

    Because of that, you need to use the Property if you want the observers to be notified. You could also add the OnPropertyChanged("Title"); line to your GenerateTitle() method, but I would recommend just using the Property.