简体   繁体   中英

copy textbox value to another when click on Button Command in WPF MVVM

I have two text box and want to copy first textbox value to another textbox whenever I click on Button and this should done by using Commands in WPF.

This is my scenario :

  1. First textbox binds the value from Person class.
  2. Button shows simple MsgBox which verifies that Command executed properly.
  3. Well here, I want to pass first textbox value to 2nd textbox (using Command) ?

XML File:

<Window x:Class="PrismDemo.Views.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:vm="clr-namespace:PrismDemo.ViewModels"
        Title="MainWindow" Height="350" Width="525">
    <Window.DataContext>
        <vm:Person x:Name="vmmmm1" />
    </Window.DataContext>
    <Grid>


<TextBox x:Name="fName" Grid.Row="1" Height="30" Width="100" Text="{Binding Path=FirstName, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>

<Button Name="Submit" Grid.Row="2" Height="30" Width="100" Content="Submit Me" Command="{Binding submitCommand}" CommandParameter="{Binding Text, ElementName=fName}"/>

<TextBox x:Name="display" Grid.Row="3" Height="30" Width="100" Text="{}" />

Person class (ViewModel):

public class Person:INotifyPropertyChanged
{
    private string _firstName;
    private string _copyName;  
    public ICommand submitCommand {get;set;}
    public Person()
    {
        _firstName = "Ronaldo";
        submitCommand = new RelayCommand(MyMethod, canExecuteMethod);
    } 

    public string FirstName
    {
        get 
        { 
            return _firstName; 
        }
        set
        { 
            _firstName = value;
            OnPropertyUpdated(FirstName);
            //OnPropertyUpdated(CopyName);
        }
    }

    public string CopyName
    {
        get
        {
            return _copyName;
        }
        set
        {
            OnPropertyUpdated(CopyName);
        }
    }

    private void OnPropertyUpdated(string property)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(property));
        }       
    }

    private bool canExecuteMethod(object parameter)
    {
        return true;
    }

    private void MyMethod(object parameter)
    {
        MessageBox.Show("Welcome to Command Demo...");
        //if (parameter == null) return;
        //_copyName = parameter.ToString();           
        this._copyName = _firstName;                    
    }

    public event PropertyChangedEventHandler PropertyChanged;
}

Any help will be appreciated. Thank you !!

You don't need CommandParameter here.

<Button Name="Submit" Grid.Row="2" Height="30" Width="100" Content="Submit Me" Command="{Binding submitCommand}" />

Add the Display property:

    public string Display
    {
        get
        {

            return _display;
        }
        set
        {
            _display = value;
            OnPropertyUpdated(Display);
        }
    }

Fix the binding in the second TextBox:

<TextBox x:Name="display" Grid.Row="3" Height="30" Width="100" Text="{Binding Display}" />

Update MyMethod:

       private void MyMethod(object parameter)
       {
           MessageBox.Show("Welcome to Command Demo...");
           Display = FirstName;                    
       }

Here is how to copy text from one textBox to another.

this is dataContext behinde MainWindow

 public class TestVM : INotifyPropertyChanged
    {
        public TestVM()
        {
            CopyCommand = new RelayCommand<string>(OnCopyExecuted);
        }

        private void OnCopyExecuted(string commandParameter)
        {
            TextUpdate = commandParameter;
        }

        private string _textUpdate;

        public string TextUpdate
        {
            get { return _textUpdate; }
            set
            {
                if (_textUpdate != value)
                {
                    _textUpdate = value;
                    OnPropertyChanged();
                }
            }
        }


        public RelayCommand<string> CopyCommand { get; private set; }


        public event PropertyChangedEventHandler PropertyChanged = delegate { };
        public virtual void OnPropertyChanged([CallerMemberName] string propertyName = "")
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }

    }

Generic RelayCommand that can take parameters

public class RelayCommand<T> : ICommand
    {
        private Action<T> _executeMethod;
        private Func<T, bool> _canExecuteMethod;

        #region RelayCommand ctor

        public RelayCommand(Action<T> executeMethod)
        {
            _executeMethod = executeMethod;
        }

        public RelayCommand(Action<T> executeMethod, Func<T, bool> canExecuteMethod)
        {
            _executeMethod = executeMethod;
            _canExecuteMethod = canExecuteMethod;
        }

        #endregion

        public void RaiseCanExecuteChanged()
        {
            CanExecuteChanged(this, EventArgs.Empty);
        }


        #region ICommand Members

        bool ICommand.CanExecute(object parameter)
        {
            var Tparam = (T)parameter;
            if (_canExecuteMethod != null)
                return _canExecuteMethod(Tparam);
            if (_executeMethod != null)
                return true;
            return false;
        }

        void ICommand.Execute(object parameter)
        {
            if (_executeMethod != null)
                _executeMethod((T)parameter);
        }

        public event EventHandler CanExecuteChanged = delegate { };

        #endregion
    }

and MainWindow xaml just to show purpose

<Window.DataContext>
        <local:TestVM />
    </Window.DataContext>
    <Grid>
        <TextBox x:Name="txt1"
            Height="35"
                 Width="150"
                 Margin="49,62,318,224" />
        <TextBox Text="{Binding TextUpdate}"
            Height="35"
                 Width="150"
                 Margin="313,62,54,226" />
        <Button Command="{Binding CopyCommand}"
                CommandParameter="{Binding ElementName=txt1,Path=Text}"
                Content="Copy"
                Grid.Row="0"
                Margin="208,157,198,132" />
    </Grid>

It's working. Now you can implement it as it fits your needs.

You were almost right ....Its working at my place properly , Just make following changes in you code Just remove command parameter... we dont need it and Bind the copied string.

<TextBox Grid.Row="1" Height="30" Width="100" Text="{Binding FirstName}" />

<Button  Grid.Row="2" Height="30" Width="100" Content="Submit Me" Command="{Binding submitCommand}"/>

TextBox  Grid.Row="3" Height="30" Width="100" Text="{Binding CopyName}" />

In View model make following changes...

public class Person:INotifyPropertyChanged{
 private string _firstName;
        private string _copyName=string.Empty;

        public Person()
        {
            _firstName = "Ronaldo";
            submitCommand = new RelayCommand(MyMethod, canExecuteMethod);
        }

        public string FirstName
        {
            get
            {

                return _firstName;
            }
            set
            {
                _firstName = value;
                OnPropertyChanged("FirstName");
            }
        }
        public string CopyName
        {
            get
            {

                return _copyName;
            }
            set
            {
                if (_copyName != value)
                {
                    _copyName = value;
                    OnPropertyChanged("CopyName");
                }
            }
        }
        public ICommand submitCommand { get; set; }



        private void MyMethod(object param)
        {
            MessageBox.Show("Welcome to Command Demo...");
            CopyName = FirstName;
        }
        private bool canExecuteMethod(object parameter)
        {
            return true;
        }

 public event PropertyChangedEventHandler PropertyChanged;
 protected void OnPropertyChanged(params string[] propertyNames)
        {
            PropertyChangedEventHandler handler = PropertyChanged;

            if (handler != null)
            {
                foreach (string propertyName in propertyNames) PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
                handler(this, new PropertyChangedEventArgs("HasError"));
            }
        }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM