P
P
Pitonist2242020-02-12 21:20:22
WPF
Pitonist224, 2020-02-12 21:20:22

How to bind to a property of another class?

There are several radiobuttons that need to change the property (MethodName) in the MethodViewModel class via binding when clicked. But in order to change the property, you need to execute the ChangeMethodName method, which is located along the MainViewModel.MethodViewModel.ChangeMethodName path, because in the file MainWindow.xaml.cs I have written

public MainWindow()
        {
            InitializeComponent();

            DataContext = new MainViewModel();
        }


How can I do that?
And, in general, is it right to create 2 ViewModel classes and then shove MethodViewModel into the MainViewModel ?

The code:
public class MainViewModel
    {
        public MethodViewModel MethodViewModel { get; set; }
    }

public class MethodViewModel : INotifyPropertyChanged
    {
        public ICommand ChangeMethodName { get; private set; }
        private string _methodName;
        public string MethodName
        {
            get => _methodName;
            set
            {
                _methodName= value;
                OnPropertyChange("MethodName");
            }
        }

        public MethodViewModel()
        {
            ChangeMethodName = new RelayCommand(ExecuteChangeMethodName, CanExecuteChangeMethodName);
        }

        #region PropertyChangedImplementation
        public event PropertyChangedEventHandler PropertyChanged;
        private void OnPropertyChange(string propertyname)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyname));
            }
        }
        #endregion

        private bool CanExecuteChangeMethodName(object parameter)
        {
            if (parameter != null)
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        private void ExecuteChangeMethodName(object parameter)
        {
            Method = (string)parameter;
        }
    }

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
SlNik, 2020-02-13
@SlNik

Perhaps this method will suit you:
1 - Change private to public in the ExecuteChangeMethodName method
2 - Cast types not to string, but to radiobuttons
3 - Pass the radiobuttons to which you want to change the Name as parameters

MainViewModel DataContext = new MainViewModel();
            Button button = new Button();
            button.Name = "Имя №1";
            DataContext.MethodViewModel.ExecuteChangeMethodName(button);

  public void ExecuteChangeMethodName(object parameter)
        {
            Button button = (Button)parameter;
            button.Name = "Новое имя";
        }

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question