繁体   English   中英

将ViewModel属性绑定到视图

[英]Binding ViewModel property to a View

我有以下内容(页面的基类和viewmodel类):

  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));
        }
      }
  }

然后是实际页面

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

XAML如下:

  <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}" ... />

如果在后台代码中,我执行以下操作

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

效果不明显。

相反,如果我将对象'VM'分配给DefaultViewModel(这是一个ObservableCollection),事情就可以解决:

 this.DefaultViewModel["VM"] = VM;

即,在最后一种情况下,使用{Binding DefaultViewModel.VM.ShowProgress,ElementName = pageRoot}我设法使进度环反映VM实例的状态。

我想念一些东西。

您页面中的ViewModel必须实现为属性才能使绑定工作。 更改

public MySuperPageViewModel VM = new MySuperPageViewModel();

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM