【问题标题】:How to do loose coupling of command programmatically?如何以编程方式进行命令的松散耦合?
【发布时间】:2020-02-17 07:15:55
【问题描述】:

我正在使用 Xamarin 制作移动应用程序。并使用 Prism 实现 MVVM,在 Views 和 ViewModels 之间松散绑定。 在一个视图中,我从后面的代码以编程方式创建按钮,如下所示:

var button = new Button {
  Text = e.ToString(),
  Command = 
};                
Container.Children.Add(button);

按钮已创建,但我还没有找到将命令属性绑定到 ViewModel 上的命令的方法。我想松散地绑定它。根据 MVVM,View 对 ViewModel 一无所知。 如果我还想参数化命令,情况会发生很大变化吗? 有没有办法做到这一点?任何帮助将不胜感激。

【问题讨论】:

  • “根据 MVVM,View 无法知道有关 ViewModel 的任何信息。”你在哪里读到的?您认为为什么会这样?
  • 我认为它是这样工作的。如果我错了,请纠正我。
  • View 可以同时了解 ViewModel 和 Model。理想情况下,ViewModel 不应该了解 View,Model 也不应该了解 ViewModel。
  • 另外,我总是更喜欢将项目控件、列表框等绑定到视图模型上的某个列表,而不是在后面的代码中创建按钮,这是反 mvvm。
  • @Haukinger 也许我会那样做。

标签: c# mvvm xamarin.forms prism loose-coupling


【解决方案1】:

您可以在ViewModel 中创建Command,然后使用Command 属性在您的视图中设置绑定,例如:

在您的视图(您的页面)中:

LoginViewModel viewModel = new LoginViewModel();
BindingContext = viewModel
Button loginButton = new Button
 {
   Text = "LOGIN",
 };
loginButton.SetBinding(Button.CommandProperty, new Binding("LoginFormCommand"));

ViewModel(LoginViewModel)中:

public class LoginFormViewModel 
 {
   public ICommand LoginFormCommand { get; private set; }
   private string _user;
   private string _pass;
   public LoginViewModel()
     {
      LoginFormCommand = new Command(LogUserIn());
     }
   public string User {
    get => _user; 
    set
     {
      if (_userName != value){ _userName = value;}
      OnPropertyChanged();
     }
    }
  public string Pass {
   get => _pass; 
   set
    {
     if (_userName != value){ _userName = value;}
     OnPropertyChanged();
    }
  }
 public LogUserIn()
  {
   bool IamLoggedIn = AFunctionThatCallsAWebService(User, Pass);
  }
 }

【讨论】:

    猜你喜欢
    • 2011-01-01
    • 1970-01-01
    • 2017-06-05
    • 2013-05-06
    • 2020-10-26
    • 2011-02-22
    • 2012-02-27
    • 1970-01-01
    • 2013-07-29
    相关资源
    最近更新 更多