简体   繁体   English

单击WPF MVVM中的Button Command时,将文本框值复制到另一个

[英]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. 我有两个文本框,并且每当我点击Button时想要将第一个文本框值复制到另一个文本框,这应该通过使用WPF中的命令来完成。

This is my scenario : 这是我的情景:

  1. First textbox binds the value from Person class. 第一个文本框绑定Person类中的值。
  2. Button shows simple MsgBox which verifies that Command executed properly. Button显示简单的MsgBox ,用于验证Command是否正确执行。
  3. Well here, I want to pass first textbox value to 2nd textbox (using Command) ? 那么,我想将第一个文本框值传递给第二个文本框(使用Command)?

XML File: XML文件:

<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): Person类(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. 这里不需要CommandParameter。

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

Add the Display property: 添加Display属性:

    public string Display
    {
        get
        {

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

Fix the binding in the second TextBox: 修复第二个TextBox中的绑定:

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

Update MyMethod: 更新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 这是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 可以接受参数的Generic RelayCommand

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 和MainWindow xaml只是为了显示目的

<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... 在View模型中进行以下更改......

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"));
            }
        }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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