Modify DataContext of a View from ViewModel WPF

0

Good afternoon, classmates. I would like to know how I can modify the DataContext of a view with its ViewModel, from another ViewModel or from the same ViewModel.

public partial class Window2 : UserControl
{   
    public Window2()
    {
        Window2ViewModel vm2 = new Window2ViewModel();
        DataContext = vm2;
        InitializeComponent();
    }      
 }

Thanks. Greetings César

    
asked by CésarIriso 05.09.2018 в 19:09
source

2 answers

0

If you declare it outside the constructor you can access the properties of the VM in any method of the class and thus modify it:

public partial class Window2 : UserControl
{   

    Window2ViewModel vm2 = new Window2ViewModel();
    public Window2()
    {

        DataContext = vm2;
        InitializeComponent();
    }      

    private void Button_Click(object sender, EventArgs e)
    {
        vm2.PropiedadViewModel = valor;
    }
 }
    
answered by 06.09.2018 в 14:58
0

Thanks for the reply. But the code still does not work for me.

The program is a test to be used later in another project. Basically they are two UserControl inside a window, each one with its respective ViewModel. I implement the INotifyPropertyChanged interfaces and ICommand.

In view1

<Button Grid.Column="0" Margin="30" Height="120"    CommandParameter="Button1ViewModelIzdo" Command="{Binding Btn1Command}">

In the ViewModel1:

   public class Window1ViewModel : NotifyBase
   {
    public delegate void EventHandler(object sender, CustomEventArgs e);
    public event EventHandler ThrowEvent;// = delegate { };

    private ICommand _btn1Command;
    public ICommand Btn1Command
    {
        get
        {
            return _btn1Command ?? (_btn1Command = new  RelayCommand((parameter) => Bnt1Action(parameter)));
        }
    }

    private void Bnt1Action(object parameter)
    {
        String msg = parameter as String;
        ThrowEvent?.Invoke(this, new CustomEventArgs(msg));
    }

In Vista2 there is a TextBlock

  <TextBlock TextAlignment="Center" x:Name="Data" Text="{Binding   Path=Data,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"></TextBlock>

And in the ViewModel2

  public class Window2ViewModel : NotifyBase
{
    private Window1ViewModel _Thrower;

    public Window2ViewModel()
    {
        _Thrower = new Window1ViewModel();
        _Thrower.ThrowEvent += ( emisor, e) => { ChangeData(emisor , e);      };
    }

    private string _data;

    public string Data
    {
        get { return _data; }
        set{
                if (_data != value)
                {
                    _data = value;
                    OnPropertyChanged("Data");
                }
            }
     }

    private void ChangeData(object emisor, CustomEventArgs e)
    {
        Data = e.msg;
        MessageBox.Show("Hell0");
    }
}   

The CustomEventArgs class has a msg propedad.   But the event does not launch me. What do I do wrong?

    
answered by 07.09.2018 в 14:25