Implementing INotifyPropertyChanged on a static property in a Singleton? - wpf

New to WPF and struggling with the following:
A StatusBarItem displays a simple timer (seconds since window loaded). The binding source property and backing DispatcherTimer are sitting in a Singleton class and are static, which seems reasonable as there is only one StatusBar per application. The class implements INotifyPropertyChanged as it's a one-way binding to the StatusBarItem.
WPF 4.5 can bind to static properties, using static events (see here).
This does not work because INotifyPropertyChanged is not static, so the event cannot be static, so the property cannot be static. The solution is to keep the timer static, but make the property not static.
What is the point of introducing binding to static properties in 4.5 if they cannot rely on INotifyPropertyChanged? Is there a static version of INotifyPropertyChanged? I must be missing something, but don't know what. Thanks for any clarification.

Yes you are missing something, the page you link to describes how you define events that notify WPF that a static property has changed.
For a property named MyProperty, either create an Event as below
public static event EventHandler MyPropertyChanged;
or a generic event called
public static event EventHandler<PropertyChangedEventArgs> StaticPropertyChanged
InotifyPropertyChanged is NOT used for static properties only one of the aboved named events

You do not need to implement INotifyPropertyChanged interface, just declare events like in the documentation.

You could wrap the static property in an instance property, but the design is the true problem here. Why have static properties in a singleton? By definition, there should only be one instance of a singleton in a process, making static properties (other than a static property to hold the instance of the singleton) pointless.

Related

Is dependency property same as a CLR property which emits a PropertyChanged event as callback?

The question is related to WPF Data Binding and MVVM pattern.
I am bit confused now distinguishing between the Dependency property defined in the XAML.cs file as well as a CLR property defined in the view model which is bound to some property of a component
For example say, I have a textbox in MyPage.xaml. So I created a dependency property to bind the textbox text property in the MyPage.xaml.cs maybe some String. The next time, I created a viewModel MyPageViewModel.cs which implements the INotifyPropertyChanged interface and
created a CLR property there(String), which emits an event PropertyChanged when it changes or the property is set with a new value. So are these both the same? Is there any difference?
I have 3 questions
Is the Dependency Property same as CLR property which emits a PropertyChanged event when it changes?
Whether Dependency property is written in the view itself(MyPage.xaml.cs) or can it be included in the view
model(MyPageViewModel.cs)?
In MVVM pattern, we use the CLR properties more which emits an event during property change. So can dependency property be replaced
by such kind of CLR properties?
Thanks in advance.
An dependency property is on a DependencyObject from which all WPF UI elements derive from (and only works there), as it's static and saves it's value in a kind of collection assigned to a specific DependencyObject (on which the dependency property is defined). Dependency properties can be defined in a class outside of the actual DependencyObject to extend it's functionality without modifying the original user control class.
When you write a user control and want a ViewModel to allow to bind a value and receive notifications when it's changed, then you create a dependency property.
Imagine it like an USB cable, where you have a male plug and a female receptacle. The CLR property is like the plug and the dependency property is like the receptacle.
A dependency property allows you to store that's associated with a control but isn't part of the instance. As you can see on the MSDN Examples
public static readonly DependencyProperty IsSpinningProperty =
DependencyProperty.Register(
"IsSpinning", typeof(Boolean),
...
);
public bool IsSpinning
{
get { return (bool)GetValue(IsSpinningProperty); }
set { SetValue(IsSpinningProperty, value); }
}
the dependency property is static and GetValue and SetValue are methods of DependencyObject (base class on which all WPF UI elements are based on).
Depencency Properties (and attached properties/attached behavior) can also be used to extend the functionality of a UserControl without inheriting from the actual user control type, i.e. notifying the ViewModel when a certain value changes which is not provided by the original user control.
Is the Dependency Property same as CLR property which emits a PropertyChanged event when it changes?
No, it's not the same. They are both 2 sides of the databinding engine. A DP is defined on the view to allow a view model to bind a INPC Property (Property that rises PropertyChanged event)
Whether Dependency property is written in the view itself(MyPage.xaml.cs) or can it be included in the view model(MyPageViewModel.cs)?
DP are part of the View-Layer as they depend on DependencyObject, which is part of the WPF framework and hence view concern. While technically nothing prevents you from using them in the ViewModel, this causes a tight coupling of your ViewModel towards a certain View technology, so it doesn't fully comply MVVM pattern.
Be aware though that unit testing Dependency Properties may be quite difficult as they don't store the values on the class they are defined on but in some kind of dictionary where the GetValue/SetValue methods warp around.
Last but not least, since DependencyObject is the base class of all UI it is as well as most of the classes that derive from it thread affine, which means you can only access it from the thread you created which may cause you much pain in both unit test (especially if the tests run in parallel like MSTest used to do. Dunno if its still true as of today) and in your code.
In MVVM pattern, we use the CLR properties more which emits an event during property change. So can dependency property be replaced by such kind of CLR properties?
In ViewModels you could and you should use INotifyPropertyChanged. If you are developing a user control, you shouldn't replace DPs with "CLR" properties, because this makes the property not work with databinding in XAML.
If your UI elements should expose a property which can be used with data binding you have to use dependency properties (or attached properties which are pretty similar, but you place attached properties on i.e. the child elements. Grid.Row and Grid.Column are examples of attached properties).

Bind to static generic instance of a class

I use this code in my views' (which are UserControl) constructors:
this.DataContext = The<Chart1ViewModel>.Instance;
Where the The<> is a generic static per-type singleton storage which also needs to implement INotifyPropertyChanged to notify of it's instance replacement.
I would like to XAML this code like, how can I do that? I have never before did bind anything to a generic static classes.
If I can't, how could I create a Binding to that static class' Instance property?
As far as I know you'll have problems using generics in XAML. Nevertheless you can use static classes. By wrapping a property around the generic you could do something like this:
<Control DataContext="{x:Static The.Chart1ViewModel.Instance}" />

WPF+MVVM: How to use plain old ViewModelBase when DependencyProperty is needed

I am using a 3rd party WPF control whose MVVM support relies on dependency properties on the VM it is bound to. The sample that comes with the control uses a ViewModelBase class derived from DependencyObject so all is well.
My ViewModelBase implements INotifyPropertyChanged and for various reasons it is unrealistic to change it to DependencyObject.
My question is how do I use my ViewModels with this WPF control? I guess what I need is something like "embedding a dependencyobject" or "plugging dependency properties" in a plain old ViewModel.
By the way my MVVM application is interface based, i.e. everywhere SomeViewModel is ISomeViewModel.
In general, a properly designed control shouldn't require binding to a DependencyProperty, as a DP can bind to any property without issue. As such, I'd revisit whether this is truly a bug in the control implementation first, and correct that.
However, if you must do this, realize you're going to violate MVVM - using DependencyObject within a ViewModel is, by its very nature, injecting view specific framework elements into the VM. Once you decide you're okay with doing this, you can always have your ViewModel expose a DependencyObject as a property, and bind to a DependencyProperty defined on that DependencyObject instead of directly to your VM's property.

WPF MVVM: Notify property changed one property everytime some other property is changed

I have a ViewModelBase class where I define RaisePropertyChanged method for the INotifyPropertyChanged interface. Most MVVM people are pretty familiar with this.
I also have a Validating ViewModel that inherits from ViewModelBase. It implements a interface and some methods to validate it's properties. It has a IsValid property the is only a getter who checks if there are any rule violations. However if I would wan't to bind to this property in the Views it would have to get updated at some time. This would basicly be everytime some other property is changed, or at least properties that I validate against. One simple solution would be to just Notify IsValid inside the RaisePropertyChanged method but it is defined in ViewModelBase where IsValid hasn't been defined.
Would any of you have a good solution for this dilemma?
If you are following the standard event handling pattern, your RaisePropertyChanged method will be marked as virtual (it should probably be a protected virtual method), so you'll be able to override that method in your validating view model, call the base implementation, and then invoke the PropertyChanged event for the IsValid property.
I'm not quite sure what you are doing, but if it is general validation, you would be better off using a framework such as DataAnnotations.

Dependency property in app.xaml.cs

I am new to WPF and the below question may look silly for many, please pardon me.
How can I create a dependency property in app.xaml.cs?
Actually, I tried to created it. The below code,
public static DependencyProperty TempProperty =
DependencyProperty.Register("Temp", typeof(string), typeof(App));
public string Temp
{
get { return (string)GetValue(TempProperty); }
set { SetValue(TempProperty, value); }
}
throws the below compile time errors:
The name 'GetValue' does not exist in the current context
The name 'SetValue' does not exist in the current context
Can anybody help me in this?
Thank you!
DependencyProperties can only be created on DependencyObjects, and since Application (which your App class inherits from) doesn't implement it, you can't create a DependencyProperty directly on the App class.
I assume you want this property to support binding. If this is the case, you have two options:
Implement INotifyPropertyChanged in App.xaml.cs
Create a DependencyObject derived class with your properties on it, and expose it as a standard read-only property of your App. The properties can then be successfully bound by "dotting-down" to them.
i.e if your new property is called Properties, you can bind like so:
<TextBlock Text="{Binding Properties.Temp}" />
If the property needs to be the target of a Binding, then option #2 is your best bet.
You class that contains dependency properties must inherit from DependencyObject.

Resources