none
How to set up command binding for this wpf button? RRS feed

  • Question

  • I have a simple wpf/mvvm app that only calculates the squareroot of a number. I enter a number in a textbox, click a button and display the result in a textblock.  But the button is not firing at all.  I have two properties (Number and Result) and one command.  I added default values to the two properties to see if they were binding to the textbox and textblock on startup.  That works OK.  But the command binding for the button not working at all.  The code sample is not using a DataContext -- just Window.Recources.

    I would be very grateful if someone could explain what I need to change/modify in this project for the button to bind to the command.  Following is the source code and the xaml.

    Many Thanks

    using System;
    using System.Windows.Input;
    using System.ComponentModel;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace calcSqrt
    {
        class ViewModel : INotifyPropertyChanged
        {
            private Model _model;
            private double _result = 123;
            private double _number = 9;
            private dlgCommand _calculateSquareRootCommand;
    
            public ViewModel()
            {
                _model = new Model();
            }
    
            public double Result
            {
                get { return _result; }
                private set
                {
                    if (_result != value)
                    {
                        _result = value;
                        if (PropertyChanged != null)
                        {
                            PropertyChanged(this, new PropertyChangedEventArgs("Result"));
                        }
                    }
                }
            }
    
            public double Number 
            {
                get
                {
                    return _number;
                }
                set
                {
                    _number = value;
                    if (PropertyChanged != null)
                    {
                        PropertyChanged(this, new PropertyChangedEventArgs("Number"));
                    }
                }
            }
    
            public ICommand CalculateSqareRootCommand
            {
                get
                {
                    if (_calculateSquareRootCommand == null)
                    {
                        _calculateSquareRootCommand = new dlgCommand(param => this.CalculateSquareRoot());
                    }
                    return _calculateSquareRootCommand;
                }
            }
    
            private void CalculateSquareRoot()
            {
                Result = _model.CalculateSquareRoot(Number);
            }
    
            public event PropertyChangedEventHandler PropertyChanged;
            private void NotifyPropertyChanged(string propertyName)
            {
                if (PropertyChanged != null)
                {
                    PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
                }
            }
        }
    
        class Model
        {
            public double CalculateSquareRoot(double number)
            {
                return Math.Sqrt(number);
            }
        }
    
        public class dlgCommand : ICommand
        {
            private readonly Action<object> _execute;
            private readonly Predicate<object> _canExecute;
    
            public dlgCommand(Action<object> execute)
                : this(execute, null)
            {
            }
    
            public dlgCommand(Action<object> execute, Predicate<object> canExecute)
            {
                if (execute == null)
                    throw new ArgumentNullException("execute");
                _execute = execute;
                _canExecute = canExecute;
            }
    
            public bool CanExecute(object parameter)
            {
                return _canExecute == null ? true : _canExecute(parameter);
            }
    
            public void Execute(object parameter)
            {
                _execute(parameter);
            }
    
            public event EventHandler CanExecuteChanged
            {
                add { CommandManager.RequerySuggested += value; }
                remove { CommandManager.RequerySuggested -= value; }
            }
        }
    }
    

    <Window x:Class="calcSqrt.MainWindow"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            xmlns:viewModel="clr-namespace:calcSqrt"
            Title="MainWindow" Height="350" Width="525">
    
        <Window.Resources>
            <viewModel:ViewModel x:Key="sampleViewModel" />
        </Window.Resources>
        
        <StackPanel Orientation="Vertical">
            <TextBlock Text="{Binding Source={StaticResource sampleViewModel}, Path=Result}" />
            <StackPanel Orientation="Horizontal">
                <Label Content="Number:" />
                <TextBox Text="{Binding Source={StaticResource sampleViewModel}, Path=Number}" Width="50" />
                <Button Content="Calculate" Command="{Binding Source={StaticResource sampleViewModel}, Path=CalculateSquareRootCommand}" />
            </StackPanel>        
        </StackPanel>
          
    </Window>


    Rich P

    Wednesday, March 26, 2014 3:54 PM

Answers

  • You have misspelled the name of the ICommand property (an 'u' is missing in CalculateSquareRootCommand):

            public ICommand CalculateSquareRootCommand
            {
                get
                {
                    if (_calculateSquareRootCommand == null)
                    {
                        _calculateSquareRootCommand = new dlgCommand(param => this.CalculateSquareRoot());
                    }
                    return _calculateSquareRootCommand;
                }
            }


    • Edited by Magnus (MM8)MVP Wednesday, March 26, 2014 4:01 PM
    • Marked as answer by Rich P123 Wednesday, March 26, 2014 4:13 PM
    Wednesday, March 26, 2014 4:01 PM

All replies

  • You have misspelled the name of the ICommand property (an 'u' is missing in CalculateSquareRootCommand):

            public ICommand CalculateSquareRootCommand
            {
                get
                {
                    if (_calculateSquareRootCommand == null)
                    {
                        _calculateSquareRootCommand = new dlgCommand(param => this.CalculateSquareRoot());
                    }
                    return _calculateSquareRootCommand;
                }
            }


    • Edited by Magnus (MM8)MVP Wednesday, March 26, 2014 4:01 PM
    • Marked as answer by Rich P123 Wednesday, March 26, 2014 4:13 PM
    Wednesday, March 26, 2014 4:01 PM
  • As always, thank you very much.  Now working correctly. 

    Rich P

    Wednesday, March 26, 2014 4:14 PM