metaphori
metaphori

Reputation: 2811

Binding ViewModel property to a View

I have the following (a base class for pages and a viewmodel class):

  public class MySuperPage : Page {
      public MySuperPageViewModel VM = new MySuperPageViewModel();

      ..........
      ..........

      public class MySuperPageViewModel {
        protected bool _ShowProgress = false;
        public bool ShowProgress {
            get { return _ShowProgress; }
            set {
                _ShowProgress = value;
                OnPropertyChanged("ShowProgress");
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;

        public void OnPropertyChanged(string property) {
            if (PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs(property));
        }
      }
  }

Then an actual page

  public class MyPage : MySuperPage(){
      public MyPage() : base() {
          this.InitializeComponent();
      }
  }

The XAML is the following:

  <my:MySuperPage
xmlns:my="using:MyNamespace"
x:Name="pageRoot"
x:Class="MyPages.MyPage"
DataContext="{Binding DefaultViewModel, RelativeSource={RelativeSource Self}}"
....>

     <ProgressRing IsActive="{Binding VM.ShowProgress, ElementName=pageRoot}" ... />

If in the code-behind I do actions such as

this.VM.ShowProgress = true; // or false

the effects are not visible.

Instead, things work if I assign object 'VM' to DefaultViewModel (which is an ObservableCollection):

 this.DefaultViewModel["VM"] = VM;

I.e., in this last case using {Binding DefaultViewModel.VM.ShowProgress, ElementName=pageRoot} I manage to have the progress ring reflect the state of the VM instance.

I feel to miss something.

Upvotes: 0

Views: 123

Answers (1)

Gerrit F&#246;lster
Gerrit F&#246;lster

Reputation: 964

Your ViewModel in your page must be implemented as a property to make the binding work. Change

public MySuperPageViewModel VM = new MySuperPageViewModel();

to

private MySuperPageViewModel _vm = new MySuperPageViewModel();
public MySuperPageViewModel VM { get { return _vm; }}

Upvotes: 1

Related Questions