Good morning companions. 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.
The program is a test to be used later in another project. Basically they are two UserControl inside a window, each with its respective ViewModel. Implement the INotifyPropertyChanged and ICommand interfaces with NotifyBase and RelayCommand.
In view1
<Button Grid.Column="0" Margin="30" Height="120" CommandParameter="Button1ViewModelIzdo" Command="{Binding Btn1Command}">
In ViewModel1:
public class Window1ViewModel : NotifyBase
{
public delegate void EventHandler(object sender, CustomEventArgs e);
public event EventHandler ThrowEvent;
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 View2
<TextBlock TextAlignment="Center" x:Name="Data" Text="{Binding Path=Data,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"></TextBlock
In 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. What am I doing wrong ?
Many thanks in advance. Greetings César.
What I have tried:
Use delegates and events Search for examples in stackoverflow and codeproject