-1

I am making a mobile app using Xamarin. And using Prism to achieve MVVM with loose binding between Views and ViewModels. In one View, I am creating buttons programmatically from the code behind, like so:

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

The buttons get created, but I have yet to find a way to bind the command property to a command on the ViewModel. I want to bind this loosely. According to MVVM the View cannot know anything about the ViewModel. Would things change a lot if I also wanted to parameterize the command? Is there a way to achieve this? Any help would be appreciated.

Martijn
  • 739
  • 9
  • 26
  • 2
    "According to MVVM the View cannot know anything about the ViewModel." Where did you read this? And why do you think this is the case? – Euphoric Oct 21 '19 at 08:12
  • I thought it worked that way. Correct me if im wrong. – Martijn Oct 21 '19 at 08:30
  • 1
    The View can have knowledge of both the ViewModel and the Model. The ViewModel ideally shouldn't have knowledge of the View and the Model shouldn't have knowledge of the ViewModel. – Michael Phillips Oct 21 '19 at 08:34
  • Also, I'd always prefer binding an items control, list box etc. to some list on the view model to creating buttons in code behind, that's anti-mvvm. – Haukinger Oct 21 '19 at 08:36
  • @Haukinger Maybe I'll do that then. – Martijn Oct 21 '19 at 08:58
  • Do you still want to set the command from code? – FreakyAli Oct 21 '19 at 09:04
  • could it work ? – Leo Zhu Nov 01 '19 at 01:03
  • In the end we decided on buttons defined in XAML, using Command="{Binding someCommand}" to bind them to commands. Thanks for the help guys. Also, why the down vote? Is it because I didn't completely understand MVVM? – Martijn Nov 14 '19 at 10:13

1 Answers1

1

you could create the Command in your ViewModel,then uses a Command property to set the binding in your View,for example:

in your View(your page):

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

in 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);
  }
 }
Leo Zhu
  • 15,726
  • 1
  • 7
  • 23