-1

Hi im working on an Wpf MVVM project, but i can't figure it out how to bind a button with the Command attribute in Xaml to a RelayCommand in the Viewmodel, i found multiple answer's online but i don't get it (implementing the ICommand interface and canexecute and stuff..) , the thing is that i have an already created project made by other developers where they simply , bind the button in Xaml like so :

heres the full code in the View :

<Window x:Class="MvvmLight3.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
    xmlns:mvvm="http://www.galasoft.ch/mvvmlight"
    xmlns:ignore="http://www.galasoft.ch/ignore"
    mc:Ignorable="d ignore"
    Height="300"
    Width="300"
    Title="MVVM Light Application"
    DataContext="{Binding Main, Source={StaticResource Locator}}">

<Window.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source="Skins/MainSkin.xaml" />
        </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>
</Window.Resources>

<Grid x:Name="LayoutRoot">

    <TextBlock FontSize="36"
               FontWeight="Bold"
               Foreground="Purple"
               VerticalAlignment="Center"
               HorizontalAlignment="Center"
               TextWrapping="Wrap" ><Run Text="WelcomeTitle"/><InlineUIContainer>
            <Label Content="{Binding welcome}"/>
        </InlineUIContainer></TextBlock>
    <Button Content="Button" Command="{Binding The_Command}" HorizontalAlignment="Left" Margin="170,80,0,0" VerticalAlignment="Top" Width="75">

    </Button>
</Grid>

and in the ViewModel the full code is :

    using GalaSoft.MvvmLight;
    using GalaSoft.MvvmLight.CommandWpf;
    using MvvmLight3.Model;
    using System.Windows.Input;

namespace MvvmLight3.ViewModel
{
    /// <summary>
    /// This class contains properties that the main View can data bind to.
    /// <para>
    /// See http://www.mvvmlight.net
    /// </para>
    /// </summary>
    public class MainViewModel : ViewModelBase
    {
        private readonly IDataService _dataService;

        /// <summary>
        /// The <see cref="WelcomeTitle" /> property's name.
        /// </summary>
        public const string WelcomeTitlePropertyName = "WelcomeTitle";

        private string _welcomeTitle = string.Empty;
        private string _welcome = "this work";
        /// <summary>
        /// Gets the WelcomeTitle property.
        /// Changes to that property's value raise the PropertyChanged event. 
        /// </summary>
        public string WelcomeTitle
        {
            get
            {
                return _welcomeTitle;
            }
            set
            {
                Set(ref _welcomeTitle, value);
            }
        }
        public string welcome
        {
            get
            {
                return _welcome;
            }
            set
            {
                Set(ref _welcome, value);
            }
        }

        /// <summary>
        /// Initializes a new instance of the MainViewModel class.
        /// </summary>
        public MainViewModel(IDataService dataService)
        {
            _dataService = dataService;
            _dataService.GetData(
                (item, error) =>
                {
                    if (error != null)
                    {
                        // Report error here
                        return;
                    }

                    WelcomeTitle = item.Title;
                });
        }
        private RelayCommand _The_Command;
        public RelayCommand The_Command
        {
            get
            {
                return _The_Command
                    ?? (_The_Command = new RelayCommand(
                    () =>
                    {
                        //some Code
                    }));
            }
        }
        ////public override void Cleanup()
        ////{
        ////    // Clean up if needed

        ////    base.Cleanup();
        ////}
    }
}

in my case the execution dont enter the RelayCommand.

the code in the ViewModelLocator.cs

    /*
  In App.xaml:
  <Application.Resources>
      <vm:ViewModelLocatorTemplate xmlns:vm="clr-namespace:MvvmLight3.ViewModel"
                                   x:Key="Locator" />
  </Application.Resources>

  In the View:
  DataContext="{Binding Source={StaticResource Locator}, Path=ViewModelName}"
*/

using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Ioc;
using Microsoft.Practices.ServiceLocation;
using MvvmLight3.Model;

namespace MvvmLight3.ViewModel
{
    /// <summary>
    /// This class contains static references to all the view models in the
    /// application and provides an entry point for the bindings.
    /// <para>
    /// See http://www.mvvmlight.net
    /// </para>
    /// </summary>
    public class ViewModelLocator
    {
        static ViewModelLocator()
        {
            ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default);

            if (ViewModelBase.IsInDesignModeStatic)
            {
                SimpleIoc.Default.Register<IDataService, Design.DesignDataService>();
            }
            else
            {
                SimpleIoc.Default.Register<IDataService, DataService>();
            }

            SimpleIoc.Default.Register<MainViewModel>();
        }

        /// <summary>
        /// Gets the Main property.
        /// </summary>
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance",
            "CA1822:MarkMembersAsStatic",
            Justification = "This non-static member is needed for data binding purposes.")]
        public MainViewModel Main
        {
            get
            {
                return ServiceLocator.Current.GetInstance<MainViewModel>();
            }
        }

        /// <summary>
        /// Cleans up all the resources.
        /// </summary>
        public static void Cleanup()
        {
        }
    }
}

the project is MVVMLight (wpf451) template . Thank you.

J.Doe
  • 37
  • 10
  • what hapens if you remove `, () => (SelectedPanel != null)` – TheGeneral Aug 07 '18 at 11:19
  • that's an exemple , it doesn't change anything , it makes the button enabled if the selectedPanel is not null else the button is desabled. – J.Doe Aug 07 '18 at 11:27
  • At the top of your xaml, did you add the datacontext? I.E. DataContext="{Binding Source={StaticResource Locator}, Path=Main}" – Kevin Cook Aug 07 '18 at 11:28
  • yes , : DataContext="{Binding Main, Source={StaticResource Locator}}" also it's linked in the ViewModelLocator . – J.Doe Aug 07 '18 at 11:36
  • this button isn't inside some sort of template, is it? – Kevin Cook Aug 07 '18 at 11:44
  • This should be working. Try putting a breakpoint on the line `return _LaunchCommand`, if that doesn't get hit when you run your program then there's a problem with your DataContext. – Mark Feldman Aug 07 '18 at 12:08
  • Also your Button tag doesn't have a closing bracket at the end, what's the rest of the XAML? – Mark Feldman Aug 07 '18 at 12:09
  • @Kevin Cook the Button is inside a stackpanel inside a grid element ,there is no template , + Mark Feldman , the button have a tag , i forgot to add it to the question, and i also tryed checking the Command with the breakpoint , but the execution don't reach it , also when i bind a text element from the view to the view model the binding Work. – J.Doe Aug 07 '18 at 12:51
  • Please provide a [MCVE](https://stackoverflow.com/help/mcve) of your issue. – mm8 Aug 07 '18 at 13:01
  • Hi again, i Edited the Question and provided the full code of the issue. thank you all – J.Doe Aug 07 '18 at 13:41
  • @J.Doe what actually you want now. – Eldho Aug 07 '18 at 13:45
  • the binding between the button in the view and the Relaycommand in the ViewModel don't work. – J.Doe Aug 07 '18 at 13:47

1 Answers1

0

It worked, it's something silly, actually if you notice my relay Command (The_Command) was empty and although it had a comment inside it (//some Code), a breakpoint on the get or return never went through when I click the button.

Solution: after I added a functioning code inside the Command it worked: added for example a simple MessageBox.Show. so the Binding was correct. For the info I'm using the VisualStudio Enterprise 2017 .

Dominik
  • 1,016
  • 11
  • 30
J.Doe
  • 37
  • 10