UIElement vs FrameworkElement in WPF/Silverlight - wpf

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

Related

UserControl, ContentControl and MVVM

I'm kind of a beginner with the WPF platform. I've done a few Windows Forms apps that were very basic and now I'm working on a much more complex app for my current work.
I'd like to implement an MVVM model, but I'm getting lost in the different articles on how to do so.
Here's a screenshot of the app interface:
The section on the left is a ListView containing 6 sections that correspond to different UserControl. I would like the section on the right to display the UserControl that corresponds to the selected Item.
Each UserControl is stored in a separate XAML file.
By looking online, I found that I should use a ContentControl in my MainWindow, but every attempt I've made has been unfruitful. I know there's more than one way to skin a cat.
Which method would you use? Do you have any concrete examples or sources where I can find how to make it work?
The only difference between UserControl and ContentControl is the OnCreateAutomationPeer method. This method is responsible for UI automation.
Although this method is rarely used in practice, it is customary to use UserControl to represent some complex data types.
A typical use for a UserControl is to retrieve data (in normal CLR types) through the data context.
And the Content property specifies (using XAML) a visual tree to represent that context.
And each such UserControl is declared as a derived type (just like a Window).
If necessary, additional properties (CLR and DP) and other members (event handler methods, for example) are added to such a UserControl.
The base class ContentControl itself and others of its successor are used somewhat differently.
The data in them goes directly to the Content property.
And their visualization is set by the data template in the ContentTemplate property.
While DataTemplate's can be quite complex, they are usually much simpler than the XAML markup of the UserControl.
And, besides the task of visualization, you cannot add additional logic (properties, fields, methods).
Here's a photo of the app interface: ...
In this UI, I don't see where the ContentControl can be applied.
On the left is a navigation bar consisting of buttons.
It is usually implemented directly in the Window from an ItemsControl or ListBox.
On the right (while an empty area) is the region for the page content.
Usually, when you click on a button in the navigation bar, the corresponding UserControl is set to this region.
At a lower level, deeper in the visual tree, for smaller elements, it is quite possible that a ContentControl is needed.
P.S. Just in case, I will clarify, in view of the comment below.
By area for pages, I do not in any way mean the use of Frame + Page.
This is a very specific pair and it is extremely rarely justified to use it.
In combination with MVVM, its use is even more difficult, since this pair does not support DataContext inheritance.
And this is the main way for the View to interact with the ViewModel.

Pattern for using dependency property for non simple type on a WPF user control

I am a newbie to WPF, and am trying to learn the standard idioms. I have a user control that allows the user to enter a mailing address, composed of six text boxes. I have also defined an interface IMailAddress, and a concrete class MailAddress that is a set of properties for the standard mail address fields. (US only for the moment.)
I figure by having an interface it means I could have some database class that holds everything about a person but implements this interface for the specific needs of this control.
What is the idiomatic way to tie this type into the control? I can certainly implement it as a dependency property, but does that make any sense with a type like this? Would I be better making it a standard property, and then raising a routed event when the value changed?
I'm not so much concerned about this specific example, but more generally what is considered best practice for these types of scenario.
Having your user control expose an IMailAddress property as a dependency property is perfectly valid. WPF itself does similar things; for example, ItemsControl expects you to bind a collection to it, so it exposes an ItemsSource dependency property of type IEnumerable.
User controls/custom controls are a good way to represent views, and don't let the MVVM freakazoids tell you otherwise :) Besides, there's no reason this can't work perfectly fine with MVVM - for example:
<local:MailAddressEditor
MailAddress="{Binding Path=Customer.BillingAddress}"
/>
One thing you may like to look at, though, is using a Custom Control instead of a UserControl. This will allow you to build a 'lookless' control that focuses on the logic behind editing an address, and allow users of your control to create Styles independently for rendering the control. When people use your control, they might use:
<local:MailAddressEditor
MailAddress="{Binding Path=Customer.BillingAddress}"
Style="{StaticResource SimpleInlineAddressEditor}"
/>
<local:MailAddressEditor
MailAddress="{Binding Path=Customer.BillingAddress}"
Style="{StaticResource ComplicatedAddressEditorWithGoogleMapsSelector}"
/>
In this case, we have one control, with two styles (and probably two ControlTemplates) to give the fields a different layout.
Custom controls are a great asset to a WPF developer - not everything has to be done via MVVM. Just try to stay conscious of the kind of code going into your custom control - if it's getting a little too logic-y, you might want to move some of that into a view model.
DependencyProperties are sort of fading away as INotifyPropertChanged is taking over with MVVM patterns. You should look at MVVM toolkits if you want to start using proper separation between your interface, data access, and business logic. You can still use DependencyProperties, but I would recommend you build a ViewModel to implement your interactions with your user control. One of the goals of MVVM is making testability easier by providing a ViewModel that can be verifed with unit tests outside of XAML-land.
A great starter MVVM toolkit for WPF is MVVM Light. A heavier weight MVVM toolkit would be Prism.

Extending user controls in WPF

I have built a User Control composed, as usual, of a XAML part and a code-behind part. Now, I need to create another User Control which shares some of the functionalities of the former, but which has different looks and might also have additional features in the code-behind.
My first idea was to create an interface to gather the common functionalities of the two types of controls. Is this the right way to go? And how would I manage the different XAML parts I should have? Any advice is welcome.
I would like to add another contribution which I think might be useful to others encountering my same situation.
One other possible solution, which in my opinion is suitable if the controls you are going to create are not particularly complex, is to create a base User Control containing the common features that you want to share: such control will be written entirely in C#.
This, in fact, allows inheritance in User Controls composed of both XAML and code behind. In the XAML of the inherited control, rather than having
<UserControl> ... </UserControl>
You will have
<MyProject: MyBaseControl x:Class="MyProject.MyExtendedControl"> ... </MyProject: MyBaseControl>
and then in the code behind you will also need to specify the following:
class MyExtendedControl : MyBaseControl
Hope this helps.
User controls don't lend themselves well to inheritance in WPF, you can do some hacks to make it work, but overall you'll probably be better off using a Custom Control instead. It's easier to specify different XAML for inherited controls using this technique. The easiest way to get started with a custom control is to add a new item to your project of type "Custom Control (WPF)" and it will add the control and the XAML gets added to Themes/generic.xaml for you.
To inherit from this control, the easiest way is to add another new Custom Control (WPF) and then change the code behind to inherit from your parent control instead of Control.
There are a number of ways to split up the pieces to make them easier to work with.
MVVM, as mentioned in a comment, relies upon Data Binding to separate the input controls from logic. By setting the appropriate class which implements INotifyPropertyChanged into the DataContext of you control, you can change the behaviour. Your DataContext class or ViewModel could implement Visibility properties to show and hide different parts of the input if the differences are not too great between the uses.
Another way to break apart functionality is by Aggregation. See StackOverflow 269496
You could build smaller controls that implement common functionality and then build larger special purpose controls by combining the smaller controls (i.e. aggregating them) to make the larger control. Aggregation will work for both the code-behind and the Data Binding approaches.

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.

Dependence on DependencyObject and DependencyProperty

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

Resources