I could have done this post yesterday but that would have been a long essay. Today we are going to look at displaying static data on XAML pages.
In C# when you have data that does not change, one tends to use const
or static readonly
. const
causes compiler to replace all occurrences of variable usage with the actual data at compile time. That means you assemblies has no lookups at run-time. Static read-only is a static variable that can also be set in constructor – is read-only otherwise.
Now based on my previous experience doing WinForms and Webforms, normally I tend to set those directly in XAML. Say you want to content of a button or a textblock text (label). So the ideal way would be.
- Take View Model
- Define consts
- Set bindings to consts
- Compile and reload
Eureka.. there’s nothing..
Well XAML bindings make a big fuss of INotifyPropertyChanged interface. From sample I know that it works with properties so could it be that ?
Lets start:
- Take View Model
- Define consts
- Define properties
- Set property in the constructor to consts
- Set bindings to properties
- Compile and reload
There.. much better..
Lesson, const and compiler time optimisations are no good.. you need to define properties and additionally call PropertyChanged events and what not including set the properties at VM Creation in order to display data the proper MVVM way. A Single task of setting a text to a textblock or a button is translated into a handful tasks..
Update 1:
My friend @Scottisafool … suggested an alternative approach that he tends to use
- Define resources in App.xaml
- Set bindings to resources
- Compile and reload
This also works.. sure it means that all your strings are in one place but that’s still not MVVM
So it turns out there is not right way but there is a wrong way!! Everything else but code-behind as the last resource is the pukka MVVM way. Wrap up for today I think.
Update 2:
More messages suggesting that the mechanism to declare labels is to either hard code those or use Resources. That’s all fine.. I could use ResourceDictionary just in case the future me might want to localise the app.
That however still leaves the need to support of real consts impossible. There isn’t any support for those in bindings wrt View Model