【问题标题】:Passing Value From View To View Model将值从视图传递到视图模型
【发布时间】:2012-11-30 06:44:49
【问题描述】:

我有一个带有文本框和按钮的 Xaml 页面 当用户单击按钮时,文本框的值应该传递给它的 viewModel。如何做到这一点?

【问题讨论】:

    标签: silverlight mvvm


    【解决方案1】:

    xaml:

    <TextBox Text={Binding TextBoxAContent} />
    <Button Command={Binding ButtonCommand} />
    

    查看模型代码应该是这样的:

    class MainPageViewModel : ViewModelBase
    {
        private string _textBoxAContent;
        public string TextBoxAContent
        {
           get {return _textBoxAContent;}
           set {
                  _textBoxAContent = value;
                  RaisePropertyChanged("TextBoxAContent");
               } 
        }
    
        public ICommand ButtonCommand
        {
           get
           {
                return new RelayCommand(ProcessTextHandler);
           }
        }
    
        private void ProcessTextHandler()
        {
           //add your code here. You can process your textbox`s text using TextBoxAContent property.
        }
    }
    

    您还应该通过视图控件的DataContext 属性将视图模型分配给视图。 (仅在构造函数中)

    public MainPage()
    {
        DataContext = new MainPageViewModel();
    }
    

    UPD

    附言RelayCommand & ViewModelBase - 来自MVVM Light的类

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-03-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多