Suppose I have VM which has implemented INotifyPropertyChange:
public class MyViewModel{
public MyClass{get;set;}
...
}
but plain class MyClass not implemented INotifyPropertyChange, It only hold some properties, like:
public class MyClass
{
public MyClass()
{
}
public string P1 { get; set; }
...
}
in xaml, DataContext is MyViewModel. I set binding like:
Text = "{Binding MyClass.P1}"
Then in MyViewModel constructor, I set up instance of MyClass and fire property change like
this.RaisePropertyChanged("MyClass");
but the value of P1 does not display in UI. How to implement something like this.RaisePropertyChanged("MyClass.P1") in this case?
You can't.
You need to implement INotifyPropertyChanged in the class that owns the property.
If you can't make that class implement INotifyPropertyChanged, you should create a separate ViewModel class that wraps it and implements INotifyPropertyChanged.
There is no way to do this. The best option would be to either wrap this value in your ViewModel, which would allow you to raise the PropertyChanged event directly on the ViewModel.
However, if this is not an option for one reason or another, the other option is to call:
this.RaisePropertyChanged(string.Empty);
This will refresh all of the bindings on the View, including MyClass.P1. This is not always a great solution from a performance standpoint, however, as it forces a full binding refresh.
You could have an event with a name following this template:
public event EventHandler <PropertyName>Changed;
public event EventHandler P1Changed;
The binding will "auto-detect" the P1Changed event and use it for data binding.
All you need to do is raise the P1Changed event when needed.
Add a property of type MyClass to your ViewModel. In the setter of your property is where you would call RaisePropertyChanged().
For example,
public MyClass SomeName
{
get
{
return this._SomeName;
}
set
{
if (value != this._SomeName)
{
this._SomeName = value;
this.RaisePropertyChanged("SomeName");
}
}
}
private MyClass _SomeName;
Related
My team uses ReactiveUI and I want to try using its APIs when the property in one item in a ObservableCollection changes:
I have a ViewModel deriving from ReactiveObject with this property:
public class ViewModel : ReactiveObject
{
public bool PageEnabled { get; set; } // the actual implementation uses custom logic, a backing field and raises PropertyChanged accordingly
}
And there's another property in a parent view model which I try to subscribe to like this:
public class ParentViewModel : ReacitveObject
{
public ObservableCollection<ViewModel> DocumentPages { get; set; }
public ParentViewModel()
{
DocumentPages.ToObservableChangeSet(vm => vm.PageEnabled).Subscribe(changeSet => UpdateSelection());
}
}
Tl;dr: whenever the PageEnabled property changes in any of the items in that collection, I want to execute the aforementioned UpdateSelection method. However, the subscription I've attempted and pasted here doesn't invoke that method when the PageEnabled property changes. The method is only called a couple of times when the VM is initialilzing, but that's not enough.
My question is, how do I get the UpdateSelection to be called when the PageEnabled property changes?
(I'm aware I can manually subscribe/unsubscribe to the PropertyChanged event whenever an item is added/removed from the DocumentPagese collection, but according to ReactiveUI's documentation https://www.reactiveui.net/docs/handbook/collections/ it should be possible to do this in a more declarative manner, yet that doesn't seem to work.)
My app is a translation app. It contains a translation list that is passed to different viewmodel. Those viewmodels migth modify those lists including add and remove operations. For this purpose, I convert this list to an ObservableCollection in the constructor and my list is no longer modified. I know converting to an ObservableCollection creates a new object and the references are no longer the same. It is working perfectly for the concerned view, but once I want to change to another view, the list isn't updated. I was wondering what was the best way to solve this problem?
I thought I could create a custom ObservableCollection that would contain the corresponding list and automatically update it when an add or remove operation would be done. Something that'd look similar to this.
View
public partial class MainWindow : Window
{
private void ListViewItem_PreviewMouseDown(objectsender,MouseButtonEventArgs e)
{
// this is where I instanciate the viewModel, and the
// list<Translation> isn't modify once I close the view
DataContext = new ModifyWordVM(translations);
}
}
ViewModel
public class ModifyWordVM: INotifyPropertyChanged
{
private ObservableCollection<TranslationVM> translations;
public ObservableCollection<TranslationVM> Translations
{
get { return translations; }
set { translations = value; OnPropertyChanged("Translations"); }
}
public ModifyWordVM(List<Translation> translations)
{
// Converting list to ObservableCollection
Translations = ConvertionHelper.ConvertTo(translations);
}
}
I'd like to know what is the cleaner way to get the modified list back.
You should encapsulate the traslations and their operations. To do this just introduce a class e.g. TranslationService which is shared between all relevant view models. To omit a smelly Singleton I added an instance of the service to the App.xaml resources.
The idea is that all modifications of the translation list take place in one location or type. The same type that is the binding source for the view. When adding a new translation the view should invoke a ICommand on the view model. This command will invoke the AddTranslation method on the TranslationService. Same for remove. Any changes to the translation collection will now reflect across the application.
If you also want to catch modifications of the actual translations (e.g. rename or edit) the TranslationService need to handle the PropertyChanged event of the ObservableCollection items as well.
When an items property changed the TranslationService must respond by raising the PropertyChanged event for the ObservableCollection property Translations. This would require the items to implement INotifyPropertyChanged too.
App.xaml
Shared TranslationService instance
<Application.Resources>
<TranslationService x:Key="TranslationService">
<TranslationService.DatabaseService>
<DatabaseService />
</TranslationService.DatabaseService>
</TranslationService>
</Application.Resources>
MainWindow.xaml.cs
public partial class MainWindow : Window
{
private void ListViewItem_PreviewMouseDown(objectsender,MouseButtonEventArgs e)
{
// Instantiate the view model and initialize DataContext from XAML instead.
// This method became redundant.
}
}
MainWindow.xaml
<Window.DataContext>
<ModifyWordVM>
<ModifyWordVM.TranslationService>
<!-- Reference the shared instance -->
<StaticResource ResourceKey="TranslationService" />
</ModifyWordVM.TranslationService>
</ModifyWordVM>
</Window.DataContext>
ModifyWordVM.cs
public class ModifyWordVM: INotifyPropertyChanged
{
public ModifyWordVM()
{}
public AddTranslation(Translation translation) => this.translationService.AddTranslation(translation);
public RemoveTranslation(Translation translation) => this.translationService.RemoveTranslation(translation);
public TranslationService TranslationService {get; set;}
public ObservableCollection<TranslationVM> Translations => this.translationService.Translations;
}
TranslationService.cs
public class TranslationService
{
public TranslationService()
{}
public AddTranslation(Translation translation)
{
// Add translations
}
public RemoveTranslation(Translation translation)
{
// Remove translations
}
private DatabaseService databaseService;
public DatabaseService DatabaseService
{
get => this.databaseService;
set
{
this.databaseService = value;
this.Translations = databaseService.getTranslations;
}
}
private ObservableCollection<TranslationVM> translations;
public ObservableCollection<TranslationVM> Translations
{
get => this.translations;
set
{
this.translations = value;
OnPropertyChanged("Translations");
}
}
}
Currently I'm coding pretty much with WPF Applications in MVVM style.
I want to extend my current BaseViewModel with some new stuff that makes things easier and faster.
One functionality I want to add is to observe all properties (with a specific attribute) and call the PropertyChanged event when the property is changed by default.
(This functionality is more about laziness, so it's not that important but I don't know how to accomplish this)
Currently I define a properties in the subclass like this:
private string _foo;
public string Foo
{
get { return _foo; }
set { _foo = value; OnPropertyChanged(); }
}
I plan to define (because it's faster and less code) the properties like this:
[Observe]
public string Foo { get; set; }
Is there any valid way to call the property changed event by default for every "marked" property in each sub class when the "set" method is called?
You probably want to take a look at Fody.
It injects INotifyPropertyChanged code into properties at compile time.
After a major edit to this quesiton, I'm hoping it's now clear.
I'm very lost with binding in WPF when 1 change should affect multiple properties.
I regularly use VVM to bind my ViewModel to my View and I would say I'm OK with it.
I am trying to implement a state controller. This means that, what ever settings I made in part of my UI, the reflection is through out.
For example in my part of my UI, I can toggle a feature on or off, such as "show images"
When I make this change, I'd like everything in my application to be notified and act accordingly.
So, my StateController class will have a property
public bool ShowImages
And in my View, I'd likely have something like
<image Visible ="{Binding ShowImages", Converter={StaticConverter ConvertMe}}" />
The problem I have is how I go about making the StateController alert all of my ViewModels of this.
Currently, in each ViewModel I'm assuming I'd have to have the same property repeated
public bool ShowImages
EG
public class StateController : BaseViewModel
{
public bool ShowImages{get;set;}//imagine the implementation is here
}
public class ViewModelB : BaseViewModel
{
public bool ShowImages{}//imagine the implementation is here
}
public class ViewModelB : BaseViewModel
{
public bool ShowImages{}//imagine the implementation is here
}
So, my question is, if I updated ViewModelB.ShowImages, how would I first inform the StateController which in turn updates all ViewModels.
Is this something the INotifyPropertyChanged can do automatically for me since they all share the same propertyName, or do I have to implement the logic manually, eg
public static class StateController
{
public bool ShowImages{get;set;}//imagine the implementation is here
}
public class ViewModelA : BaseViewModel
{
public bool ShowImages
{
get { return StateController.ShowImages; }
set { StateControllerShowImages = value;
OnPropertyChanged("ShowImages"); }
}
}
public class ViewModelB : BaseViewModel
{
public bool ShowImages
{
get { return StateController.ShowImages; }
set { StateControllerShowImages = value;
OnPropertyChanged("ShowImages"); }
}
}
I hate the idea of the above implementation but it does show what I'm trying to achieve. I just hope there is a better way!
The PropertyChange notification is only raised for that one object model.
So raising a change notification of the "Name" property of ClassA will only update the UI in cases where it's bound to that specific ClassA.Name. It won't trigger a change notification for any ClassB.Name, or other instances of ClassA.Name.
I would suggest using a Singleton here for your StateModel, and having your other models subscribe to the StateModel.PropertyChanged event to know if it should update, like this answer.
public ViewModelA
{
public ViewModelA()
{
StateController.Instance.PropertyChanged += StateController_PropertyChanged;
}
void StateController_PropertyChanged(object sender, NotifyPropertyChangedEventArgs e)
{
// if singleton's ShowImages property changed, raise change
// notification for this class's ShowImages property too
if (e.PropertyName == "ShowImages")
OnPropertyChanged("ShowImages");
}
public bool ShowImages
{
get { return StateController.Instance.ShowImages; }
set { StateController.Instance.ShowImages = value; }
}
}
If I understood you correctly, you are looking for a mechanism that allows your different ViewModels to communicate between each other.
One possible way would be to implement the Observer Pattern (a code example can be found here: "Observer pattern with C# 4"). In this way your ViewModel subscribe each other to receive change notifications from a "publisher", i.e. the ViewModel that had its value changed. You have a good control over who receives which notification from which publisher. The downside of this approach is a tight coupling between your models.
My approach would be this:
Use a message dispatcher. Your ViewModels can subscribe to a certain type of message, e.g. ShowImagesChanged. If any of your ViewModels changed the ShowImages property, that ViewModel calls the dispatcher to send out such a ShowImagesChanged message with your current values.
This way you can keep you ViewModels decoupled from each other. Still, although the ViewModels do not know each other this gives a way to exchange data between them.
Personally, I have used the Caliburn Micro MVVM framework several times for this, but there should be enough other MVVM frameworks that provide the same functionality to fit your taste.
The Calibiurn Micro documentation and how easily the dispatcher can be used is here: Event Aggregator
To avoid code repetition you can create a class derived from BaseViewModel that implements your property and have ViewModelA, ViewModelB extend it. However, this does not solve the problem of keeping each instance updated.
In order to do so, you may:
Use a static class (your current solution) or a Singleton as suggested in one of the comments. This is simple but has potential problems such as race conditions and coupling.
Have your ShowImages binding property repeated in each ViewModel and update it by subscribing to a ShowImagesChanged event. This could be published through a Command executed from the UI. I'd say this is the WPF approach and has the benefit of decoupling the ShowImages state management from its consumption.
Assign the ShowImagesupdate responsibility to a single ViewModel and subscribe to the its PropertyChanged in the other ViewModels so that they update accordingly. Better than the first option, but still huge coupling.
Why repeat properties at all? Just bind to StateController itself.
Say we have singleton StateController:
public class StateController : INotifyPropertyChanged
{
private static StateController instance;
public static StateController Instance {
get { return instance ?? (instance = new StateController()); }
}
//here`s our flag
private bool isSomething;
public bool IsSomething
{
get { return isSomething; }
set
{
isSomething = value;
PropertyChanged(this, new PropertyChangedEventArgs("IsSomething"));
}
}
private StateController(){}
public event PropertyChangedEventHandler PropertyChanged = delegate { };
}
Then in base VM class just make a reference to this controller:
public StateController Controller { get { return StateController.Instance; } }
And where needed bind like this:
<CheckBox IsChecked="{Binding Controller.IsSomething}">
Test
</CheckBox>
This way every binding will work with one property and react to one property. If you need some custom code to work you can subscribe to PropertyChanged of StateController where needed and take action.
I am having trouble with grasping the concept of a ObservableCollection inside MVVM. For start I would like to point out that I am doing this in a Windows 8/Metro App, not WPF or Silverlight.
According to microsoft documentation, this collection has the following usefulness:
"Represents a dynamic data collection that provides notifications when items get added, removed, or when the whole list is refreshed." From what I understand this helps you a lot when binding is involved. On the net I found a lot of simple examples, by creating a ObservableCollection on runtime and then working on it, but I didn't find out what is the proper way of using this collection with a repository.
Let' say I have the following repository interface that is an implementation for a ORM database backend, or a raw ADO.NET implementation
public interface IRepository<T>
{
ObservableCollection<T> GetAll();
void Create();
void Update();
void Delete();
T GetByKey(object key);
}
and a simple ViewModel that use the repository as a model
public class ViewModel
{
private ObservableCollection<Dummy> _obsListDummy;
private RelayCommand _addCommand,_deleteCommand,_updateCommand;
private IRepository<Dummy> _repositoryDummy;
public class ViewModel()
{
_repositoryDummy=Factory.GetRepository<Dummy>();
}
public ObservableCollection<Dummy> ObsListDummy
{
get
{
return _repositoryDummy.GetAll();
}
}
public RelayCommand AddCommand
{
get
{
if (_addCommand == null)
{
_addCommand = new RelayCommand(p => DoAdd();
//DoAdd method shows a popup for input dummy and then closes;
);
}
return _myCommand;
}
}
........
}
My view would be a simple XAML with a grid, also Dummy object has INotifyPropertyChanged implemented.
Right now with this implementation after adding or updating or deleting, the ObservableCollection isn't refreshing, I know I could have put IEnumerable instead, but I dont'see an elegant solution of how would make repository to sync with the ObservableCollection that is in the model, other than subscrbing to CollectionChanged and there you treat all the states, but to it seems that I would repeat myself along with the logic that I do in the repository. And to make matters even worse, let's say I would like to get some push notification from my repository, towards the ObservableCollection.
I hope I was understand about my problem.
Thanks in advance.
You should implement INotifyPropertyChanged on your ViewModel and your ObsListDummy property should inform the ViewModel about changes applied to the collection. So it should look like this:
public class ViewModel: INotifyPropertyChanged
{
// Declare the event
public event PropertyChangedEventHandler PropertyChanged;
// Create the OnPropertyChanged method to raise the event
protected void OnPropertyChanged(string name)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(name));
}
}
private ObservableCollection<Dummy> _dummyCollection;
public ObservableCollection<Dummy> DummyCollection
{
get { return _dummyCollection; }
set
{
// Set the value and then inform the ViewModel about change with OnPropertyChanged
_dummyCollection = value;
OnPropertyChanged("DummyCollection");
}
}
}
This whole INotifyPropertyChanged interface and implementation includes some dirty work like declaring event and creating a helper method to raise the event so I would suggest you to use some libraries for that like MVVM Light.
You should use a member of type ObservableCollection to store your Dummy ViewModels. In your Initialize method you read the dummies from the repository, create Dummy ViewModels and put those in the ObservableCollection. Now your view will get updated, when you use Binding to ObsListDummy (and add / remove from that collection, also note that Binding only works with public properties).
Right now, you just have a new ObservableCollection on each read, no events involved, so your View will never know about a change.
Further your ViewModel shall implement INotifyPropertyChanged.