Reputation: 3063
This is probably duplicated question, but i could not find solution for my problem.
I'm working on WPF application using MVVM pattern.
There are four views which are binded to their ViewModels. All ViewModels have BaseViewModel as parent.
public abstract class ViewModelBase : INotifyPropertyChanged
{
private bool isbusy;
public bool IsBusy
{
get
{
return isbusy;
}
set
{
isbusy = value;
RaisePropertyChanged("IsBusy");
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected void RaisePropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
}
MainView contains BusyIndicator:
<extWpfTk:BusyIndicator IsBusy="{Binding IsBusy}">
<ContentControl />
</extWpfTk:BusyIndicator>
If I set IsBusy = true in MainViewModel, BusyIndicator is shown.
If I try to set IsBusy = true from other ViewModels, BusyIndicator is not shown.
Just to notice, I can not use 3rd party libraries in my project like MVVMLight in order to use their Messenger to communicate between ViewModels.
MainView:
public class MainWindowViewModel : ViewModelBase
{
public ViewModel1 ViewModel1 { get; set; }
public ViewModel2 ViewModel2 { get; set; }
public ViewModel3 Model3 { get; set; }
public MainWindowViewModel()
{
ViewModel1 = new ViewModel1();
ViewModel2 = new ViewModel2();
ViewModel3 = new ViewModel3();
//IsBusy = true; - its working
}
}
ViewModel1:
public class ViewModel1 : ViewModelBase
{
RelayCommand _testCommand;
public ViewModel1()
{
}
public ICommand TestCommand
{
get
{
if (_testCommand == null)
{
_testCommand = new RelayCommand(
param => this.Test(),
param => this.CanTest
);
}
return _testCommand;
}
}
public void Test()
{
//IsBusy = true; - BusyIndicator is not shown
}
bool CanTest
{
get
{
return true;
}
}
}
Upvotes: 3
Views: 5739
Reputation: 9240
public class MainWindowViewModel : ViewModelBase
{
public ViewModel1 ViewModel1 { get; set; }
public ViewModel2 ViewModel2 { get; set; }
public ViewModel3 Model3 { get; set; }
public MainWindowViewModel()
{
ViewModel1 = new ViewModel1();
ViewModel2 = new ViewModel2();
ViewModel3 = new ViewModel3();
ViewModel1.PropertyChanged += (s,e) =>
{
if(e.PropertyName == "IsBusy")
{
// set the MainWindowViewModel.IsBusy property here
// for example:
IsBusy = ViewModel1.IsBusy;
}
}
//IsBusy = true; - its working
}
}
Repeate subcsription to all your viewModels.
Don't forget to unsubscribe from the events, when you don't need it more, to avoid memory leacks.
Your problem was: you binded to the MainWindowViewModel's propetry, not to inner ViewModel's properties.
Upvotes: 4