2

How to bind button to function in "MVVM style".

I just started to convert my app to mvvm style.

my code:

XAML in Page1.xaml class:

 <Button x:Name="my_button" Content="Add"  Command="{Binding msgbox}"  Margin="451,82,39,0" Width="50" Height="31"/>

ViewModelPage1.cs class:

public class ViewModelPage6
    {
        public void msgbox()
        {
            MessageBox.Show("mvvm is great");
        }     
    }

Can someone give a simpler answer then here

Thanks,

Flufy.

  • 1
    What is "hard" in linked answer? – Sinatr Apr 16 '18 at 12:27
  • usually all the logic isn't inside code behind –  Apr 16 '18 at 12:29
  • Possible duplicate of [How to Bind a Command in WPF](https://stackoverflow.com/questions/13838884/how-to-bind-a-command-in-wpf) – Sudsy1002 Apr 16 '18 at 12:29
  • With MVVM you will still have to create many classes containing code for converters, data template selectors, behaviors, etc. Just create reusable `ICommand` class once and then use it everywhere. I like [DelegateCommand](https://www.wpftutorial.net/DelegateCommand.html). "No code-behind" (pure mvvm) means avoiding code in the view. `ICommand` implementation is viewmodel stuff. – Sinatr Apr 16 '18 at 12:32
  • as Sinatr said, you need to make use of `ICommand`. Make sure that you have also declared the datacontext of your `Page1.xaml` though. If it doesn't know that it is supposed to get data from `ViewModelPage1.cs` then it will never bind. – Sudsy1002 Apr 16 '18 at 12:34
  • @Flufy : besides CodeBehind, I don't think there's a simpler way of binding a command into a VM when using MVVM. – Atlasmaybe Apr 16 '18 at 12:44

2 Answers2

0

Here's a simple example which binds a button:
https://social.technet.microsoft.com/wiki/contents/articles/32164.wpf-mvvm-step-by-step-2.aspx

Using icommand directly is a bit of a nuisance for most purposes, so you want to look into a framework which makes that easier. The sample uses mvvmlight, other frameworks are available but this is a good one. Especially for a beginner.

Andy
  • 11,864
  • 2
  • 17
  • 20
0

You cannot bind a method to the Command property of a Button directly. You will have to use an implementation of ICommand.

This should get you started..

public ICommand msgboxCommand = new DelegateCommand(msgbox);

private void msgbox()
{
...
}

See this for more details: https://www.wpftutorial.net/DelegateCommand.html

Besides, using a UI component like Messagebox in the ViewModel directly; isn't exactly MVVMish

bit
  • 4,407
  • 1
  • 28
  • 50