Reputation: 13350
Ideally I would like to place some properties in the App class for my WPF application to share between windows, dialogs, controls, etc. Is it trivial to reference those properties from other WPF components or should I just make them static for easier access?
Upvotes: 0
Views: 239
Reputation: 3152
In my opinion, the biggest issue in placing properties at the App class is that your code will be tightly coupled. Besides, the properties may be outside the scope of the App class.
If you don't care about patterns, i.e., your application do not tend to grow in complexity, using properties in the App class may be a quick and easy solution. But if you do this in an already complex (or growing) code, it may lead you to a lot of headache.
If by making the properties static you mean put them in some class and reference it in another class, you get a less tightly coupled code, but not loosely enough.
Upvotes: 1
Reputation: 11211
If you expose properties on your App class, you can bind to these properties declaratively by setting the DataContext:
DataContext="{x:Static Application.Current}"
I do however agree with Eduardo, you are going to end up tightly coupled to your App implementation. You might be able to mitigate this by defining a static class as you can reference, but create view models for your views which internally use your static class to retrieve the values being bound to.
If most of your properties are strings, you could define them in the Resources of your application (to do this you need to change Resources from Internal to Public) and access them statically like so:
<Window
x:Class="MyApp.Shell"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008" mc:Ignorable="d"
xmlns:properties="clr-namespace:MyApp.Properties"
Title="{x:Static properties:Resources.Shell_Title}" WindowStartupLocation="CenterScreen" WindowState="Normal"
></Window>
Upvotes: 1