PropertyChanged is always null on wp7.1 but works fine on wp8

531 Views Asked by At

Disclaimer: There are a lot of questions here about PropertyChanged event which is always null and I've read most of them. But I'm posting another one (and probably different from others).

I have created a very simple data binding app. It works just fine on Windows Phone 8, but does not work at all on Windows Phone 7.1 because on WP7.1 PropertyChanged is always null.

Here is my code (I've tried to make it as simple as possible to illustrate the issue).

Xaml:

<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
    <TextBox x:Name="txtTest" Text="{Binding Text}"></TextBox>
</Grid>

Main page class:

public partial class MainPage : PhoneApplicationPage
{
    // Constructor
    public MainPage()
    {
        InitializeComponent();
        DataContext = new BindingTest();
    }
}

And, finally, the data context class:

class BindingTest : INotifyPropertyChanged
{
    private string _strTest = "Hello";

    public string Text 
    { 
        get { return _strTest; } 
        set
        {
            if (_strTest != value)
            {
                _strTest = value;
                RaisePropertyChanged("Text");
            }
        } 
    }    

    public event PropertyChangedEventHandler PropertyChanged;
    protected void RaisePropertyChanged(string name)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null) handler(this, new PropertyChangedEventArgs(name));
    }
}

As you can see I did not forget about setting the data context for the, implementing INotifyPropertyChanged interface, and call RaisePropertyChanged().

As I mentioned above, the code works on Windows Phone 8 emulator, but PropertyChanged is always null for Windows Phone 7.1 (device and emulator).

The MainPage constructor does not set up the PropertyChanged (it is already null after first assignment - DataConext = ...).

Thank you in advance for any advise.

1

There are 1 best solutions below

1
On BEST ANSWER

First, to make the matter clear: you're saying that it does not work because PropertyChanged is null. That's wrong. You must see the problem the other way: PropertyChanged is null because it doesn't work.

As to know why is doesn't work, it simply because you didn't mark your BindingTest class as public. Change the class declaration as follows and it should work:

public class BindingTest : INotifyPropertyChanged