Search code examples
c#silverlightdata-bindingwindows-phone-7

Data binding not working, What is wrong? Silverlight WP7


I'm new to Silverlight and I'm trying to use Databinding. This looks simple but it's not working and I can't find why.

In my MainPage.xaml:

<map:Map Name="bing_map" Height="578" Width="480"

         ZoomLevel="{Binding ZoomLevel, Mode=TwoWay}"
         Center="{Binding Center, Mode=TwoWay}"

         CredentialsProvider="{StaticResource BingMapsKey}" />

As you can see, I'm attempting a binding on ZoomLevel and Center.

In my MainPage.xaml.cs

The class inherit from INotifyPropertyChanged

In the constructor:

ZoomLevel = 12.0;
Center = new GeoCoordinate(0, 0);

The properties:

private double _zoom_level;
private double ZoomLevel
{
    get { return _zoom_level; }
    set {
        if (_zoom_level == value) return;
        _zoom_level = value;
        RaisePropertyChanged("ZoomLevel");}
}

private GeoCoordinate _center;
private GeoCoordinate Center
{
    get { return _center; }
    set {
        if (_center == value) return;
        _center = value;
        RaisePropertyChanged("Center"); }
}

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

Am I forgetting something?


Solution

  • Try changing the properties to public:

    private double _zoom_level;
    public double ZoomLevel
    {
        get { return _zoom_level; }
        set {
            if (_zoom_level == value) return;
            _zoom_level = value;
            RaisePropertyChanged("ZoomLevel");}
    }
    
    private GeoCoordinate _center;
    public GeoCoordinate Center
    {
        get { return _center; }
        set {
            if (_center == value) return;
            _center = value;
            RaisePropertyChanged("Center"); }
    }
    

    And also set the View DataContext: (as Ray mentioned in his answer)

    public partial class MainPage
    {
        public MainPage()
        {
            this.DataContext = this;
        }
    }
    

    It is highly recommended to use the MVVM pattern.