Defining properties of UI using Attributes - c#

For a new project, I was recently asked to investigate a method of attaching information related to UI rendering to business objects in a WPF application. For example a report class:
class ExecutionReport
{
[Displayable(Bold, Background=Color.Red)]
public String OrderId{get; private set;}
[Displayable(Normal, HAlignment=Center)]
public String Symbol {get; private set;}
// this should be hidden as it doesn't have DisplayableAttribute
public String ClientOrderId {get; private set;}]
[Displayable(Normal, HAlignment=Right,
Format("If [Position] < 0 then Background=Color.Red"),
Format("If [Position] > 0 then Background=Color.Lime"),
DisplayFormat("+#;-#;0")]
public Int Position {get; private set;}
}
This is a very new approach for me as typically in most wpf MVVM applications I have worked on there has been a clear separation of the view and viewmodel and I strive as much as possible to keep UI specific details out of the VM. Instead I would lean towards writing this using resource dictionaries and simple converters applied on the bindings in the view layer.
My questions are: Are there any wpf/mvvm frameworks out there that use this kind of an implementation? If so I'm curious to see how it would be achieved.
Are there any obvious pitfalls? The first couple things that come to my mind are
Change notification (ie. INotifyPropertyChanged to trigger an update of the view). Would the implementation of this be a lot harder now?
Difficulty in being able to leverage resource dictionaries for system wide values. For example, maybe I wanted to change the color of red being used throughout the application. I would have to ctrl + f through and find every place in business objects where it was used and change it instead of being able to modify a single StaticResource
Inability to leverage DesignTime DataContexts
Performance. Seems likes this would require heavy use of reflection which might not be as performant as typical value converters
I'm very interested to see if I'm correct on the second and third points or if both of these things could still be acheived?
Ultimately I feel that this is a bad design and I'm leaning towards writing a different implementation to show the interested party how I would typically approach this kind of problem. Just want to make sure I'm not missing something obvious that might actually make this more elegant.

IMO this seems like a horrible idea, they all seems like examples that should be implemented as XAML converters.
All of the points list seem to be valid reasons to avoid doing this.
Note: There are a set of attributes in the framework which provide some UI functionality already (very limited), see the System.ComponentModel.DataAnnotations namespace.

This approach is very popular and it's called aspect oriented programming (ASP.NET MVC leverages it a lot). The most popular library to write this fast is PostSharp (see customers case studies, there are some companies which have used it for WPF). The best thing in PostSharp is that uses compile-time weaving.
For the first point:
PostSharp got well tested NotifyPropertyChanged aspect, you can add [NotifyPropertyChanged] attribute to class and all properties will call PropertyChanged when value gets changed.
For the second point: you can always make your attribute to look for StaticResources and pass resource key in attribute.
For the third (although I'm not 100% sure about it) and fourth point: compile time weaving means that aspect is "appended" to code on compilation - like you would have written it inside method/property to which you have appended attribute. It's like post-build compiler and doesn't use reflection (if aspect you wrote doesn't use reflection) so performance is really good.
However in example you gave I'd rather go with value converters and styles like #AwkwardCoder said - but aspects(attributes) are also useful with "view" for example: they're great for validiation.

I agree that this seems like a horrible idea, and your comment ...
in most wpf MVVM applications I have worked on there has been a clear
separation of the view and viewmodel and I strive as much as possible
to keep UI specific details out of the VM. Instead I would lean
towards writing this using resource dictionaries and simple converters
applied on the bindings in the view layer
... I think sums up why and how to avoid it.
Tying your business objects directly to implementation details such as colour, horizontal alignment, or position, seems like a short-term win (but long term hell).

Related

WPF DataGrid binding with ObservableCollection using MVVM [duplicate]

I heard its the next best thing in building WPF UIs, but all existing
examples have dozens of lines of code - can I get a Hello World
for MVVM that explains in no uncertain terms what its all about?
I'm fairly new to C#/.net as well, so maybe point me to some
resources that could help too?
Much appreciated!
One sentence explanation:
MVVM is a reimagining of the well loved Model-View-Presenter (MVP) pattern that is designed to work especially well with databinding facilities supplied with WPF to separate application logic from UI design.
Longer, more useful, explanation:
The basic concept of MVVM is the break apart a WPF application into separate components each of which has one responsibility in the process of getting information on screen.
Firstly you have the model. This is a class with very limited functionality that is generally populated from some outside source such as a database or webservice. For example:
public class MessageModel
{
public string Message { get; set; }
}
On top of that you layer the ViewModel, this is where the logic of the application sits, it notifies the view of changes to the model and ensures data consistency. By implementing the INotifyPropertyChanged interface two way databinding between the ViewModel and the view is given for free by WPF:
public class MessageViewModel : INotifyPropertyChanged
{
private MessageModel _model;
public string Message
{
get { return _model.Message; }
set
{
if (_model.Message != value)
{
_model.Message = value;
OnPropertyChanged("Message");
}
}
}
}
Finally you have the View. This is a xaml file that describes the layout of the controls used to display and edit the data in the ViewModel:
<Canvas>
<TextBox Text={"Binding Message"} />
</Canvas>
The reason that you go to all this effort is that the Model is very lightweight and easily passed across domain boundaries. It is simple to send or receive it from a webservice or map it to a database table. The ViewModel, on the other hand is complex, but has few dependencies - it doesn't care where the model gets it's data from, only that it is there and it has no concept of a view at all which makes it very testable (the logic of your application doesn't rely on a UI to test). Finally the xaml is well compartmentalised and can be handed off to a designer who needs to know nothing about the logic of the application, only that the ViewModel will present certain data under certain names. This encapsulation makes it very easy to define roles in large projects, or put together a limited UI to test logic against while the real one is being polished.
MVVM is a star-fan relationship. The fan knows the star but the star does not know the fan. The fan loves his star so much that if the star changes himself ( I mean his dressing style ), the fan changes himself accordingly.
Now replace "star" with "ViewModel" and "fan" with "View" and read it once again.
One sentence? Here goes.
MVVM is a UI segregation pattern where the Xaml (View) binds to a facade (View Model) allowing the guts of your program (Model) to avoid having UI concerns leak down a layer.
The simple statement that helped me get my head around it best was "Could I unit test my business logic without the user interface?" I think this should be the question you ask while learning and designing using MVVM concepts.
This site has a great diagram that explains it.
Basically you have 3 components:
1) Model - The data model of your application. this is pretty standard and the same as any MVP or MVC app.
2) View - The XAML that defines the view/layout of your app.
3) View Model - Because WPF demands that the view attach to things in certain ways (like requires that collections implement INotifyCollectionChanged and stuff like that) it normally requires that you massage your data a little bit to get it in a form suitable for the view to display. This is where the view model codes in. It packages up the data into view models that the view can easily display. This is what your view XAML will bind to. It must respond to events from the model layer and update itself.
(Then your controllers hang on the side somewhere - ideally using WPF commands - and make changes to the model, which fires events to update the view model)
a pattern where the frontend(view) and backend(modal) communicates (back and forth) using a common mediator(view-modal).
The MVVM pattern is when the UI interfaces with an xaml-friendly intermediate object to get at your xaml-unfriendly actual data.
I would say something like: "Presentation pattern for separation of concern between user interface and it's logic"
An improved answer:
MVVM is all about the future; you want to separate your application logic from the framework so that either the framework can evolve, and your app may not have to change, or your app can evolve and you won't have to worry so much about changing the actual UI aspects.
Actually, MVVM is a refinement of a pattern that has been around for some time. I can remember evolving the pattern when I was working in MFC. There are at least two reasons for doing so. MFC or <> is fairly complex, and mixing MFC constructs in with your application logic makes the application kind of brittle. Example: replacing a listbox with a combobox (or selector in modern terms) is much more difficult if the logic for supporting the content of the list/selector is combined with the logic to manipulate list/selector itself.
Some really good one-sentence (or close to it) explanations already. I'll just add to it by saying that if you're past the basic level and you want an example of how to use MVVM in a real-world app that has menus, tool bar, options dialogs, docking tools windows, etc., take a look at SoapBox Core and this demo using SoapBox Core. It is open sourced so you can get lots of ideas.
Because you can't data-bind to your own codebehind
(only half joking here)

Exposing Data as C# Properties - Good or Bad?

I am kinda not getting my head around this and was wondering if someone could please help me understand this.
So here is the problem, I have a class in which there are no required parameters. If user does not set the fields I can take the default value and carry on. Previously, I designed the same class as Joshua Bloch's Builder Pattern (Effective Java) (immutable object). I didn't had any good reason for making the class immutable except for the fact that I didn't wanted to have telescopic constructors and I didn't wanted to expose the data of the class.
But now, a fellow programmer friend is trying to convince me that it's okay to expose the data from the class using C# properties. I am not sure about this and I still feel that I should not be allowing user to muck with data.
Maybe I am completely wrong in my understanding. Could someone please clear my doubt about this, that whether it's good or bad to expose the data from the class?
If it is good then in what case it is good? Or else if someone can please point me to the article/book that clarifies this I would really appreciate it.
Thanks!
Expose the data in the class if it is needed or of interest outside the class, and do not do so if it is not. Expose it read-only if it's only needed to be read outside, and expose it as a full read/write property if it should be able to be changed. Otherwise, keep it in a private field.
immutable classes are easier to reason about especially in a multi tasking application, but they usually pay in performance (because when you need to change the value of a field you need to build the whole class again with the new value).
So, you could be ok or (depending on what you're coding) even better off with properties but as usual there's no silver bullet.
Settable properties are also the only way to code objects for some specific frameworks or libraries (e.g. ORMs like NHibernate), because you can't control how the library/framework initializes the object.
About constructors, C# 4 has optional parameters, that could help you avoid a long chain of constructors and also communicate much more clearly the fact that the parameters are optional.
However I can't think of many cases where you would end up with classes with a long list of optional parameters. If you find that you're coding classes like that too often (especially with the builder pattern, which is very elegant looking on the consumers' side of the class but complicates the code for the class itself) you may be using the wrong design. Are you sure you are not asking your classes to have too many responsibilities?
It basically depend on what's the purpose of your Class in the application context (could you give us more details?).
Anyway reckon that you could make a property safe from external changes by declaring is setter as private:
http://msdn.microsoft.com/en-us/library/bb384054.aspx
public string UserName { get; private set; }
It's "good" when the consumer of the class needs the data. You have two possibilities to offer properties.
if you only want to offer a property for information purpose, then choose a read only property like this:
public string MyInformation { get; private set; }
If you have the need to allow the consumer to change that property, then make the setter public like that:
public string MyChangeableInformation { get; set; }
But if the consumer has no need to get the information, then hide it in your class!
But now, a fellow programmer friend is trying to convince me that it's
okay to expose the data from the class using C# properties. I am not
sure about this and I still feel that I should not be allowing user to
muck with data.
As a rule of thumb, methods should represent actions whereas properties represent data. What your friend might have tried telling you is that you can expose the data of your class to outside world and still maintain full control on how other classes are accessing the data. In your case, as other have mentioned, you can use properties with private setters, such that the caller should not be able to modify the data.

How to properly design a class that should contain dual language information

If my domain object should contain string properties in 2 languages, should I create 2 separate properties or create a new type BiLingualString?
For example in plant classification application, the plant domain object can contain Plant.LatName and Plant.EngName.
The number of bi-lingual properties for the whole domain is not big, about 6-8, I need only to support two languages, information should be presented to UI in both languages at the same time. (so this is not locallization). The requirements will not change during development.
It may look like an easy question, but this decision will have impact on validation, persistance, object cloning and many other things.
Negative sides I can think of using new dualString type:
Validation: If i'm going to use DataAnattations, Enterprise Library validation block, Flued validation this will require more work, object graph validation is harder than simple property validation.
Persistance: iether NH or EF will require more work with complex properties.
OOP: more complex object initialization, I will have to initialize this new Type in constructor before I can use it.
Architecture: converting objects for passing them between layers is harder, auto mapping tools will require more hand work.
While reading your question I was thinking about why not localization all the time but when I read information should be presented to UI in both languages at the same time. I think it makes sense to use properties.
In this case I would go for a class with one string for each languages as you have mentioned BiLingualString
public class Names
{
public string EngName {get;set;}
public string LatName {get;set;}
}
Then I would use this class in my main Plant Class like this
public class Plant: Names
{
}
If you 100% sure that it will always be only Latin and English I would just stick with simplest solution - 2 string properties. It also more flexible in UI then having BiLingualString. And you won't have to deal with Complex types when persisting.
To help decide, I suggest considering how consistent this behavior will be at all layers. If you expose these as two separate properties on the business object, I would also expect to see it stored as two separate columns in a database record, for example, rather than two translations for the same property stored in a separate table. It does seem odd to store translations this way, but your justifications sound reasonable, and 6 properties is not un-managable. But be sure that you don't intend to add more languages in the future.
If you expect this system to by somewhat dynamic in that you may need to add another language at some point, it would seem to make more sense to me to implement this differently so that you don't have to alter the schema when a new language needs to be supported.
I guess the thing to balance is this: consider the likelihood of having to adjust the languages or properties to accommodate a new language against the advantage (simplicity) you gain by exposing these directly as separate properties rather than having to load translations as a separate level.

Architectural question regarding Interfaces implementation and extensibility

I've created a sample app, just to test and try out some of wpf's capabilities. I was basically trying out the databinding in wpf, and did the rest of stuff more or less quickly. THen, i faced an arquitectural problem (yes, should have thought in advance before starting coding :) ) and i wanted to know what's the best refactoring solution for it.
I have a simple interface that returns a list of objects, based on a defined process.
public interface IDoStuff<out T>
{
IEnumerable<T> Do(string someParam);
}
i've created a couple of implementations for this interface. Then i have a view in wpf, which has a dropdown with hardcoded values, and depending on what you select, instatiates the implementation of the interface and populates some list
foreach (var item in new IDoSTuffImplementation1()<MyObj>.Do("imp 1"))
{
MyObjs.Add(item);
}
ater on MyObjs is the DataContext for a listview, and displays things and so on and so forth, but it's out of the main question.
this is all hardcoded and not very nice. If i was ever to implement a new interface, i'd need to add it to the dropdown, and create a new foreach for that specific implementation (more duplicated code)
Ok, here's my impression on making this better/refactoring for extensibility.
I was thinking a good approach would be to use some kind of MVVM pattern, making the wpf view into a view + viewmodel. the viewmodel would use some kind of IoC like spring, which would (by xml) instantiate one specific implementation of the interface, and inject it to the viewmodel, which would then call its "Do" method and everyone happy. So this way, the only thing that would be needed to do when we implement a new component, is to add it to the xml config file.
Suggestions, Comments? what's the best approach, if any?
thanks!!
Actually I don't see any architecture changes if you provide another implementation of the interface. You already have a good architecture when using MVVM, so the task you are trying to accomplish will not change the architecture, but will extend your application using the architecture.
I suggest you change you Method to a Property instead. And assign that property to ComboBox's ItemsSource property to ease up your coding using data binding.

Dependency Properties

Can anybody explain me what a dependency property is in WPF and what is its use. I know there are a lot of tutorials on google for it, but they teach how to create a dependency property. I am confused as to where I would use it. I mean will I use it in XAML? If anybody could explain me in simple terms, that would be great.
It would be nice if a simple example is shown along with XAML, with example, of how I might use the property, and what would be the effect after I use it.
Thanks a lot for all your answers..
The many links listed should give you a good idea of what dependency properties are, but in general, the easiest way to think about them I believe is the following:
Dependency properties are what you need to use for properties of user interface elements, if you want to be able to bind them using WPF's data binding. In order to be the "Target" of a data binding operation, you'll need to make the property a Dependency Property.
When you're implementing a standard class (which becomes the DataContext of a "control"), you'll want to use INotifyPropertyChanged instead of DPs. This allows that class to be a binding "Source".
In general, you'll only want to make Dependency Properties if you're making something that will be bound in XAML, as the Target of a UIelement. For example, say we have XAML like this:
<local:MyControl ControlProperty="{Binding SomeProperty}" />
Normally, ControlProperty will be a Dep. Property, since it's the binding target, and SomeProperty will be a standard CLR property (not a DP), in a class that implements INotifyPropertyChanged.
A Dependency Property does not store its value in a field, but rather in some hashtable. Thus it needs less memory, which is important especially for GUI objects, because most properties will retain their default values und thus those don't take up any more memory. Dependency properties are a bit slower though, because of boxing to and fro object and looking up in the hashtable.
The Dependency Object framework furthermore allows for a lot of features like change notifications etc. I found a good resource that explains the inner workings here: http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/c33a8359-58be-430d-b949-cb6e6f32d8aa
I agree the syntax to declare them is a bit ugly, but you can create helpers to alleviate that a bit.
This is probably the most straightforward article describing DPs:
http://joshsmithonwpf.wordpress.com/2007/06/22/overview-of-dependency-properties-in-wpf/
Personally, I use them most often when I need to expose properties so that they can be databound via XAML. For example, if I make a UserControl that I want to use in XAML, and I want to set a property on the UserControl via XAML, I expose it as a dependency property.
What you're looking for is chapter 3 of WPF Unleashed. It's a free sample chapter.
the best use I saw for it is for attaching properties to classes which you cannot modify. So if you get a third party assembly you can attach extra information to the classes and read them when you need to.

Categories

Resources