Dependence on DependencyObject and DependencyProperty - silverlight

I'm building a Silverlight application and one of my caveats from last time was that if you need anything done right in Silverlight/WPF way you'd need to model your objects as a DependecyObject and use DependencyProperty(ies)
I find this model to be rather cumbersome, requiring static fields and initializers in half the classes I use, so is it a good idea to use the good-old event-driven (observer pattern?) in place of DependencyObject?
I'm aiming to minimize code bloat and boiler plates (I hate them) and really would like to know if anyone with experience in Silverlight/WPF has any tips/techniques for keeping usage of DependencyObject and DependencyProperty to a minimum?
Is this a good idea?

Actually, in Silverlight you cannot inherit DependencyObjects, and so you should (and have to) implement INotifyPropertyChanged instead.
Implementing INotifyPropertyChanged has many advantages over DependencyObjects (I will abbreviate this DO to make it easier) and using DependencyProperties (DPs):
This is more lightweight
Allows you more freedom in modeling your objects
Can be serialized easily
You can raise the event when you want, which can be useful in certain scenarios, for example when you want to bundle multiple changes in only one UI operation, or when you need to raise the event even if the data didn't change (to force redraw...)
On the other hand, inheriting DOs in WPF have the following advantages:
Easier to implement especially for beginners.
You get a callback mechanism (almost) for free, allowing you to be notified when the property value changes
You get a coercion mechanism with allows you to define rules for max, min and present value of the property.
There are other considerations, but these are the main.
I think the general consensus is that DPs are great for controls (and you can implement a CustomControl with custom DPs even in Silverlight), but for data objects you should rather implement INotifyPropertyChanged.
HTH,
Laurent

It really depends on which objects you are referring to. If the object is intended to sit in the XAML tree, its best to use DependencyProperties (and thus inherit DependencyObject - which all UIElements do) to allow all the benefits that DependencyProperties provide (being animatable, binding, optional automatic child inheritance, etc). I highly recommend you read the MSDN overview on DependencyProperties if you haven't already.
If the object is an data entity (ie. you are binding its values TO something in the XAML tree) then there is no need to inherit from DependencyObject. If the properties on the object are read-write you may want to implement INotifyPropertyChanged, which will allow bindings to automatically update when the value changes.

I agree with Richard that it depends on the purpose of your class, but as a note it seems that you CAN inherit from DependencyObject directly in Silverlight 2.0 Release, without having to inherit from UIElement or UserControl. At least, I'm doing that in my (SilverLight 2.0 RTW) app.
System.Windows.DependencyObject on MSDN
It is not typical to derive directly from DependencyObject for most scenarios. Instead you might derive from a specific control, from one of the control base classes (ContentControl; Control; ItemsControl), from FrameworkElement, or from non-control classes that still participate in UI such as Panel or Grid. Deriving from DependencyObject might be appropriate if you are defining a business or data storage object where you want dependency properties to be active, or if you are creating a service support class that will own attached properties.
HTH

Related

viewmodel have to be public. How should I deal with that?

Pretty much it summarizes my problem here:
Double check - does it ever make sense to have internal viewmodel class?
I have controls.DLL and I'd like to keep this custom control bindings and viewmodel's internal. However, this doesn't seem to be possible.
How do you get around that? The only way I see it - don't use bindings..
Why do you have a view model for a custom control? I assume you're assigning the view model object to the DataContext property, but this is almost always a mistake: the DataContext should be available to consumers to use and abuse as they please. Stated another way, what happens if a consumer of your custom control explicitly sets the DataContext? It sounds like your control will stop working and throw a bunch of xaml binding errors.
A custom control is inherently lookless. There is no model or view model, just a view. That view is the .cs file. You supply a default look via your themes/generic.xaml file, but consumers should be able to supply their own template. If you're tying them to a view model, they also need to know how to create a view model instance and all of its dependencies. You've just created highly coupled code. DI containers can loosen the coupling, but that just downgrades the relationship between classes from "coupled" to "related". I say, why do consumers even need to know that information?
A better approach is to provide all of the properties for your control as dependency properties. Then your generic.xaml can provide a control template that uses the more efficient TemplateBinding to bind properties/objects to your control. If you need to populate these dependency properties from a business object, expose another dependency property of type IBusinessObject and set the derived values in that object's PropertyMetaData changed handler. If your IBusinessObject type contains a property which is yet another class which implements INotifyPropertyChanged, you should probably (1) rethink your object graph or (2) create a Bnding object in code using the subclass.
I think following all of the above advice will eliminate the problem about which you're concerned plus the other problems as well. Leave the view models to the UserControls. And yes, this is why custom controls are a MASSIVE headache. Doing them right is fairly involved.
Try protected internal. I suppose this should work. Although I don't think its good idea to have the ViewModel not public at all, cause one of the purposes of it is to be able to define several Views against the same ViewModel, which may come from different assemblies.

UIElement vs FrameworkElement in WPF/Silverlight

When do I derive from UIElement and FrameworkElement considering FrameworkElement inherits UIElement. Can anyone give real life examples?
This is a good page for learning about WPF Architecture, and this answer only applies to WPF. Check out the UIElement and FrameworkElement sections, as well as the rest if you have time. Here's a quote from the linked page explaining why the 2 levels exist:
To this point in the topic, "core" features of WPF – features implemented in the PresentationCore assembly, have been the focus. When building WPF, a clean separation between foundational pieces (like the contract for layout with Measure and Arrange) and framework pieces (like the implementation of a specific layout like Grid) was the desired outcome. The goal was to provide an extensibility point low in the stack that would allow external developers to create their own frameworks if needed.
In short, UIElements know how to draw themselves (because they are derived from Visual). They can also use the routed events system by providing virtual methods like OnPreviewMouseDown and OnMouseDown, and part of the layout system by implementing Measure and Arrange.
FrameworkElements extend the layout system by implementing some of the virtual methods defined in UIElement. They provide a consistent way of setting layout properties, e.g. the Margin property and the MinWidth property. Additionally, the can be styled, and they can take part in data binding.
In answer to your question, if you need any of the extra abilities that FrameworkElement add, e.g. you need styles, binding or a layout system that's easier to use, then derive from them. Otherwise, derive from UIElement as there is a slight overhead from using FrameworkElement.
Also, you should have a look at the Control class (derived from FrameworkElement), as these provide useful new layers of functionality like Templating and properties like Padding.
Familiarising yourself with the inheritance hierarchy is also a good idea, you might want to derive from other classes in it (though probably no higher up the chain than Visual).
I don't have any examples right now, but I can refer you to links that might help.
UIElement is a base class for most of the objects that have visual appearance and can process basic input in Silverlight.
FrameworkElement provides a framework of common APIs for objects that participate in Silverlight layout. FrameworkElement also defines APIs related to data binding, object tree, and object lifetime feature areas in Silverlight.
So what additional capabilities do you get? See http://forums.silverlight.net/p/205863/482651.aspx

Should your ViewModel expose XAML elements as properties or not?

Over at the StackOverflow question How can WPF Converters be used in an MVVM pattern? I've learned that Value Converters should not be used in the MVVM pattern since the functionality of a Value Converter should be handled by the ViewModel itself.
This makes sense.
But I remember reading that you should not expose XAML elements to the View, but instead expose only collections of data which the View then binds and displays using DataTemplates.
However, converters seem quite powerful (e.g. as they are used in the MVVM Template demo, see the "Messenger Sample" after unpacking it) in that they can convert objects to objects, e.g. Message objects to FlowDocument objects, or Customer objects into Visibility objects, or custom Status objects into Images, etc.
So if a ViewModel is going to take on the functionality of a Value Converter, it is going to have to expose XAML elements and properties such as StackPanel, Visibility, Color, FlowDocument, etc., right?
Does anyone see any reason why a ViewModel should not expose these rich XAML objects as Value Converters do?
Because then that limits the ViewModel to be used only with a specific visual representation.
Once you have the ViewModel emitting XAML, it puts design content into a developer's domain.
This means that the designer using Expression Blend cannot edit design assets - and the designer/developer workflow is broken.
Keeping the XAML on the page and using Value converters with data templating keeps the design separated from the code.
When your ViewModel exposes specific XAML it also limits that ViewModel to be used only in that specific instance and makes it less reusable.
Don't forget that you can use DataTemplates too. I can see some sense in keeping ValueConverters out of MVVM, but DataTemplates are all about transforming objects into GUI.
Your ViewModel can expose other objects (e.g. nested ViewModels) to the GUI, and the GUI can use <DataTemplate DataType="{x:Type SubViewModel}">... to map those objects to GUI.
Does anyone see any reason why a ViewModel should not expose these rich XAML objects as Value Converters do?
Absolutely, because it undermines all the goals of MVVM:
You're no longer unit testable, at least not easily.
You no longer have separation between logic (view model) and presentation (view). Thus, designers and developers cannot easily collaborate.
Code maintenance is more difficult because you've mixed the concerns together.
If I saw a view model returning a view, I wouldn't even classify it as MVVM.
I think one idea of mvvm/mvc/mvp etc. is to isolate the GUI code to one file/class.
If you do this can you change to some other UI without rewriting the other objects?
I think if you're passing around WPF specific objects the answer is no.
It's a value judgment you'll have to make for your self.
There is no absolute 100% rule that works for this or many other concepts when you discuss them without the perspective of why the community's mind has shifted as it has in this direction. There is no 'assumed' truth or science in 'conventional wisdom' regardless of how new or compelling it is at the time.
In other words - just do the best with your team as if your good, your already getting pulled down far more in human concerns than anything as real as this.

Need advice on implementing UI in WPF

I need some advice on implementing UIs in WPF.
So far, I've been using Code-Behinds, which is extremely easy to get-started, but hell when maintaining/changing/testing.
I've looked at MVP (and its WPF variant - MVVM), but having some trouble getting started.
Assuming I have a UI to build, here's what I think I should do:
1.
Create a "Main UI" Mediator class which specifies ALL high-level operations (LoadSettings(), SetVisibility() ) and events (not triggered by the user, e.g, model data changed) that my UI supports.
2.
Create the "Model" classes to represent the data
3.
Create "ViewModel" classes for my model classes.
4.
For complex behaviours (e.g, a sequence of operations need to be done before the UI can/should update, such as modifying items in a collection), do not rely on ViewModels to update the UI. Instead, do it manually through the Main UI Mediator class.
5.
For simple behaviours (e.g, toggling the visibility/enabled states/etc), use WPF binding to bind the ViewModels' properties directly to the UI.
In this case, the Main UI Mediator class would maintain both the ViewModel and Model objects, and delegate user interactions (to the Model) and UI update requests (to the ViewModel/View) appropriately. The Mediator class also provides a centralised interface which specifies the functionalities of the UI, while acting as a Change Manager (described in GOF's Observer Pattern) to handle complex UI behaviour/reduce redundant UI updates.
Am I on the right track? Should I tweak my approach? Change it completely? At the moment, I lack the experience/knowledge to implement huge/complex UIs, so I don't really know whether I'm on the right track.
Thanks
This is a bit long, sorry about that!
So far, I've been using Code-Behinds, which is extremely easy to get-started, but hell when maintaining/changing/testing.
Yep :) Anytime you have to name a control and write "someControl dot blah" in your code-behind, that's a code smell. It's sometimes unavoidable, but try to limit it as much as possible. Your UI is a projection of the model - ViewModels and ValueConverters are a way to deal with the impedance mismatch between the two domains.
A few problems with your approach:
Create a "Main UI" Mediator class which specifies ALL high-level operations
Instead of doing this, your Window class acts as the "Controller"; the important thing is, use Commanding to define your top-level actions. This way, you can have UserControls decoupled from the Window class, because the UserControl will just call Commands.Open.Execute(null, this), and the Window can handle it, and the UserControl will never explicitly have a dependency on the Window.
Create "ViewModel" classes for my model classes.
In MVVM, the VM part is to help you out - if you can get away with binding directly to the model (i.e. the data doesn't change or you don't mind implementing INotifyPropertyChanged in your models), then doing this (even if you have to use a few IValueConverter classes) is okay. ViewModels are mostly used when the view is so different from the model representation that it'd be ugly to hack up your model, or to "tack on" extra properties that only make sense in this particular view.
while acting as a Change Manager...
Remember that WPF does this for you, via Dependency Properties and INotifyPropertyChanged; don't reinvent the wheel; if you write an OnDataUpdate() function, this is a sign you're not using data binding properly.
e.g, a sequence of operations need to be done before the UI can/should update, such as modifying items in a collection
This is where Commanding is great - your CanExecute function can apply arbitrarily complex logic to decide whether a certain operation can be done, and if you bind it to UI elements like Menus or Buttons, they will automatically disable/enable as needed.
It hasn't been mentioned, but do all of your UI design in XAML.
There is nothing worse than seeing WPF UI's being created via code-behind.

Dependency Property Uses in WPF

I am having a hard time figuring out good reasons for the dependency property. Why the System.Controls.TextBox "Text" property a dependency property and not a normal property? What benefits does it serve being a dependency property?
One of the things I am trying to accomplish is to add a ValidationRules property to my UserControl which will contain other validation rules. Like here:
<customControls:RequiredTextBox.ValidationRules>
<validators:NotNullOrEmptyValidationRule ErrorMessage="FirstName cannot be null or empty"/>
</customControls:RequiredTextBox.ValidationRules>
The problem is that I am not sure if ValidationRules property should be DependencyProperty or just a normal property.
The above code gives the following error:
{"Cannot add element to 'ValidationRules'; the property value is null. Error at object 'LearningWPF.ValidationRules.NotNullOrEmptyValidationRule' in markup file 'LearningWPF;component/addcustomerwindow.xaml' Line 35 Position 66."}
Here is the ValidationRules property:
public static readonly DependencyProperty ValidationRulesProperty =
DependencyProperty.Register("ValidationRules",
typeof (Collection<ValidationRule>), typeof (RequiredTextBox),
new FrameworkPropertyMetadata(null));
public Collection<ValidationRule> ValidationRules
{
get { return (Collection<ValidationRule>)GetValue(ValidationRulesProperty); }
set { SetValue(ValidationRulesProperty, value); }
}
The benefits are primarily two fold:
Firstly a dependency property is only created when it is used, this means the TextBox class can be very efficient, with a low memory footprint since it has a minimal number of real properties taking up space on the heap. This is especially important in WPF where all controls are just collections of more and more specific types. If each of those inner types declared tens of properties to define behaviour and look then a high level control like a button would end up having the size of a class with something in the ballpark of a hundred properties.
Secondly dependency properties can be tied to an object other than the type that they are created for. This allows the case where a control can set a Grid.Column property, which the Grid control can read and use for layout. This means that we don't hundreds of decorator classes supplying tiny pieces of functionality required by other controls. This means that xmal is far more intuitive and readable.
Edited to address the example in your revised question:
While your validation property won't gain much benefit from being a dependency property (basically out of the reasons in all the answers so far I can only really see my comment of memory footprint coming in to play), and it certainly isn't advantageous as it is in the case of the Text property of a text box where you may want to bind it, or change it based on some other input, I would still implement it as a dependency property. My reasoning for this is simple; you don't gain much, but it also doesn't cost you anything - I have never wished I had used a basic property in a custom control whereas when I first started writing them I was constantly upgrading my basic properties to dependencies because I wanted some extra functionality.
Simply put, while the dependency property is more complex to define that a normal property I would still use it as the de facto standard for WPF controls unless there was some good reason to do otherwise. In much the same way as a property is the standard for classes, even though a field is easier to implement.
The primary benefits I would say are:
First-class data binding support.
Clean Attached Property semantics
Property values which "depend".
That last point is key
Before Dependency Properties, having a value have a local value, an animatable value, an overridable value, a styleable value, a templatable value would require the declaration of multiple Properties/Fields/Dictionary entries, as well as complex state+precedence management.
Dependency Properties give you all these features out of the box, while declaring just ONE property.
That being said, in your case, you may not want to declare your ValidationRules as a DependencyProperty if you won't need to take advantage of these features.
If you do, you'll want to have different handling for your collections (non-empty collections for example). In this particular example, I would use Reflector and see how the .NET TextBox implements their validation collections, and see if you can reuse or copy the code.
There's no point re-inventing the wheel unless you're certain your wheel will be better. My personal experience is that my reinvented wheels tend to be missing things ;).
As Martin Harris already pointed out, DependencyProperties can limit the memory footprint by throwing the property values into a dictionary, however this can (and I believe was?) done by MSFT before the advent of DependencyProperties.
Martin also mentions Attached Properties, but those were also available (at least in designer) before the advent of DependencyProperties. The Attached Property implementation using DependencyProperties is much cleaner.
Dependency Properties are required if you want to use binding to populate the value of a property. If it was just a normal property, you wouldn't be able to bind the Text property to a property of your View Model object, for example.

Resources