Dynamic controls in WPF MVVM - wpf

I have an app with MVVM which works fine. Now I want to replace one of my controls with a dynamic control. By dynamic I mean that I have no idea what control this is, only that it is a GUI control. It could be something as simple as a image, or a custom third party user control that will be created by someone else after this app is done.
Can someone shed some light on how this can be achieved in MVVM? I've done it before a long time ago using ListBox or similar (iirc) to generate GUI elements (don't remember details). But I'd like to learn the theory behind it this time.
Edit:
Lets say the View contains a list of instances of for example System.Windows.UIElement. I want to display all of these UI controls on a surface (for instance in a stacked control).

You could create a View that exposes a Content property as a placeholder (so a ContentControl might be all that is needed) The content property could then be set to the dynamic control.
You would have to add a little reflection to dynamically load the assembly and instantiate the required control.
The dynamically loaded control would have to access the data by using the DataContext property. If the dynamic control is MVVM too it might have its own ViewModel so you would have to find a way to load that too (reflexction again?) and point the DataContext of the control to the loaded ViewModel.
Does this make sense, is this what you are looking for?

Related

Is a custom `RadioButtonList` based on `ListBox` necessary in WPF?

I inherited a project that uses a RadioButtonList which inherits from a ListBox. It was taken off the web (currently cannot find a link to), and contains RadioButtonList.cs (which contains six dependency properties) and RadioButtonList.xaml (which is just styles and control templates).
This control is used in over a hundred places. It causes problems because it is not a complete and professional control. Problems such as, focus issues, keyboard navigation, and so on. (See comments.)
After much research at different times over the last couple years, it seems that this control is really not necessary. All that is needed is to set the GroupName property on a group of radio-buttons. And, the only reason why a RadioButtonList control is used is to help with data-binding a list of options through the inherited ListBox.
1) Is this control really necessary? Is there a better way?
2) Is there a professional control, open-source or otherwise, that will allow me to get the benefits of data-binding without the headaches? (We use Infragistics and DevExpress, but I am not familiar with all the controls these suites offer.)
My Answers
1a) Is this control really necessary?
If you only need one list of radio buttons, then no this control is not necessary.
If your applicaton uses many lists of radio buttons, then yes this control is necessary.
If you use a list of radio buttons in different applications, then yes this control is probably necessary.
1b) Is there a better way?
I say that deriving from a ListBox, ItemsControl, or whatever then creating styles and templates is the only way to create this control; therefore, no there is no better way.
2) Is there a professional control...
Definitely, the ListBoxEdit with the RadioListBoxEditStyleSettings.
Comments Regarding Answers
All the answers indicate that creating a RadioButtonList control is not necessary. Yet, if you need more than a couple lists of radio buttons, by the time you create the styles and control templates and maybe data template, you will end up with a collection of code artifacts that can be called a radio-button-list-control. Therefore, in my opinion, a RadioButtonList is necessary.
Moreover, my understanding is a RadioButtonList was dropped in an early WPF CTP. Which I can understand, because of the limited need for such a control that can easily be created.
Comment Regarding Accepted Answer
2) Is there a professional control...
Definitely, the ListBoxEdit with the RadioListBoxEditStyleSettings.
Lastly Comment on Mike Strobel's Answer
The RadioButtonList that I have is the end-result of his answer. While I am good at creating custom-controls, I rather let third-party component makers, such as Infragistics and DevExpress, create and support a basic control like this one.
Is this control really necessary? Is there a better way?
As #lawc points out, no, it is not necessary. It may, however, be preferable, depending on what level of flexibility you desire. A reusable style is easy enough to create, but doing it "correctly" is a bit more involved than simply setting a custom ItemTemplate.
Using Styles
An ItemsControl in WPF will wrap its items in appropriate containers. Each of the selector controls in core WPF overrides the logic which determines whether an item is capable of serving as its own container, as well as the factory code which produces new item containers. A ListBox, for example, will wrap each of its items in a ListBoxItem (unless the item itself is already a ListBoxItem). The style applied to these containers can be set for the parent ItemsControl via the ItemContainerStyle property. This differs from the ItemTemplate property, which allows you to control the appearance of the item within the container. More specifically, it overrides the content template applied to the ContentPresenter within the container.
Since a RadioButton does not derive from ListBoxItem, simply setting the ItemTemplate will produce a list of RadioButton controls embedded within ListBoxItem controls, which means they will still have the same selection chrome normally associated with ListBox controls, and possibly some layout and focus oddities. This is probably not what you want.
Instead, override the ItemContainerStyle and use it to assign a custom ListBoxItem template which embeds a RadioButton. You can probably get away with not setting the GroupName property at all, which eliminates possible name collisions. Instead, just establish a two-way binding between the RadioButton.IsChecked property and the templated parent's ListBoxItem.IsSelected property.
In order to use this technique conveniently, one generally creates a Style resource (available application-wide) which can be applied to the appropriate ListBox instances, and which sets the ItemContainerStyle. Alternatively, you can make the container style available as a global resource and set that on your ListBox instances. Either way, you need to set a property.
Using a Custom Control
While WPF evangelists often recite the philosophy of preferring custom styles over custom controls, in practice this is not always convenient. You may find it more convenient to create a RadioButtonList which extends the ListBox control, and then give it a default style which automatically applies the custom style described above. This gets you out of manually assigning the list style or container style on every ListBox instance, but it's not a huge win.
But maybe you want a bit more control over the appearance of the RadioButton items. For instance, you may want to:
Adjust the margin around the "bullet" of each RadioButton item;
Adjust the vertical alignment of the bullets relative to the content;
Support both horizontal and vertical orientations;
Automatically disable the RadioButton content for items which are not selected.
Creating your own implementation, most likely derived from ListBox, allows you to add these features easily, even after you are already using your radio list across your application. This could be done with the technique above too, though it may require an attached behavior or some attached properties, in which case you end up with a somewhat fragmented design.
Third-Party Solutions
Is there a professional control, open-source or otherwise, that will allow me to get the benefits of data-binding without the headaches?
This is not an uncommon use case, and I have no doubt there are some implementations floating around. Some may be in open source frameworks, and some may be extracted from open source applications. As for third-party implementations, I do know that Actipro ships a RadioButtonList in their Shared WPF library, which is included with all of their WPF components. When last I checked, it was not available on its own. It does, however, support all of the additional features I listed above.
I can only tell you that DevExpress uses a ListBoxEdit with a RadioListBoxEditStyleSettings to represent a group of RadioButtons. Practically it is the same as your control you are using, but i think it provides better functionality and is well tested. A RadioButton is not provided by DevExpress and in my application i use the Default RadionButton-Control provided by WPF/Silverlight.
You use the RadioListBoxEdit of DevExpress as follows:
<dxe:ListBoxEdit SelectedItem={Binding CheckItem, Mode=TwoWay}>
<dxe:ListBoxEdit.StyleSettings>
<dxe:RadioListBoxEditStyleSettings />
</dxe:ListBoxEdit.StyleSettings>
</dxe:ListBoxEdit>
More information about the ListBoxEdit of DevExpress can be found here
In my opinion you don't need this control.
You can simply use .Net ListBox to achieve all your existing functionality.
Using ListBox.ItemsSource you can data bind your options collection
Specify ListBox.ItemTemplate containing the RadioButton, in this template you can data bind your view model property to RadioButton.GroupName
IMHO, a control deriving from ItemsControl would be the cleanest approach.
Then you probably would override
IsItemItsOwnContainerOverride() with return item is RadioButton;
GetContainerForItemOverride() to return a new RadioButton() for each item and
PrepareContainerForItemOverride() to set up binding of ToggleButton.IsCheckedProperty and ContentControl.ContentProperty.
While these parts are just boilerplate code, some more efforts may lie in the implementation of the keyboard behavior.

How to bind an element from a user control to a different user control?

I need to create a basic user control with certain functionality (like dragging, minimizing and more..).
Now I need a bunch of other user controls to inherit from it and add their content.
I want an option to add new user controls that implements only a part of the base control and remains with the rest of the elements and functionality.
How can I bind a certain element (grid, stackpanael,.. whatever..) from the base user control to the new control? (without loading xaml in the code behind)
I basically want to "plant" a xaml element in a dedicated element on the base user control from a different user control.
If you write a custom control, one of the Controls you can use in the template is called a "ContentControl." Then when you use the Custom Control on a page, you can specify in xaml what the content is going to be. Thus you can put in a Grid, StackPanel, whatever in there.
But note that writing your own Custom Control is rarely done other than by 3rd party component vendors, as it requires a fairly deep knowledge of SL (for example, how to use Dependancy Properties). More commonly used is the "User Control" which is far easier to use and requires no such knowledge. I usually start by trying to accomplish what I need with a UserControl, and if I hit a roadblock, then switch over to a CustomControl.
But most of the existing controls already come with the functionality you describe - drag and drop, minimize etc. SL has a rich UI control set already, so a good place to start is by seeing if one of the existing controls has most of what you need, and then take it from there.
Greg

Custom painting in WPF view

I have a question about doing the custom painting operations in WPF MVVM View. My case is:
External manipulation of model data happens, and the observable collection of data to be shown is modified (storing some data to be shown in a diagram). I have to react to that change in my view, and custom layout the diagram elements (remove the ones not used, place new ones, calculate positions on diagram canvas). How can I do that, and what would be the best way to do it conform to MVVM pattern? I cant subclass the diagram class, as it is sealed. The diagraming framework used is MindFusion.
Edit: A solution was proposed on MindFusion Support forum, and it works.
http://mindfusion.eu/Forum/YaBB.pl?board=wpfdg_disc;action=display;num=1306412889;start=0
Last I checked MindFusion diagraming component for WPF, it supported MVVM through data binding. If you bind the diagram to a ObservableCollection you can then write custom Node Templates which are basically DataTemplate that will render YourDiagramModel items on the diagram panel.
Unlike WinForms you usually don't need to manually refresh or paint control surface in WPF custom controls.

WPF patterns: Items and ItemsSource

Well I'm designing a Custom WPF control - fore the sake of learning - that display logs message in a similar way Visual Studio does. I want to allow the user add messages by adding message istances to an Items collection, or by binding to an ItemSource. I think this is a well established pattern in many wpf controls, but I have no Idea on how achieve it. I know I can obtain the same result by adding a listview as a part of my control, but the project goal is learning, so I prefer avoid that solution. Any idea ?
Have a read around the ItemsControl, your custom control can inherit from an ItemsControl, or a derivative of it. If you create an ObservableCollection containing your items and bind that to your ItemsSource, then your list will be automatically updated. You can style the ItemTemplate and Template to give the list a different look and feel.
There's loads of info here

using MVVM and WPF for a realistic visualizations

I currently need to create a visual representation of a ferry system that displays the actual ferries their position on the sea and the state of their cargo. The ferries contain trucks and the trucks contain cars. I need to display the actual trucks and their xy postion on the deck. When the ferries are loaded the postions of the trucks are updated frequently so the look animated. Also I need to display the actual cars on the trucks. Trucks, cars and ferries have some states that need to be displayed too. So I have a hierarchical structure of data that I need to visualize in a rather realistic manner.
What would be a good way to implement this kind of stuff in WPF? Should I use MVVM with one TreeView control and create a HierarchicalDataTemplates for sea, ferry, truck and car and a ControlTemplate for the TreeView? Or should I better use UserControls and compose and update them in code instead of databinding to observable collections of the ViewModel. Do you have any experience with this? How would you do this? Could you sketch out class/control setup?
I'd recommend making a "lookless" control as opposed to making user controls. Generally I use user controls as glue/container for my lookless controls. An example of a lookless control is the Button class. It contains a default style and in Blend, you can modify the style all you like. It also supports the visual state manager so you can change how the presentation looks when states change. You can think of the codebehind of a lookless control as a mini ViewModel. Here it is ok to mix some presentation stuff and your domain classes.
If you follow this same design, you could create a Ferry lookless control. This control would have a set of it's own dependency properties (possibly listening to the OnChange of the DP).
Your Ferry control may have an ObservableCollection DP called "Trucks".
Then in your Themes\generic.xaml, create a default style for your Ferry control. Your default style may have an ItemsControl with an ItemsSource={TemplateBinding Trucks}. The ItemsControl panel template, could be your own custom panel for arranging the Trucks, or maybe you use a Canvas. For the ItemsControl items template, you would have something like this:
<DataTemplate>
<mynamespace:TruckControl/>
</DataTemplate>
You Truck control, would also be a lookless control with it's own default style, and it's data context will already be set, so you can directly do the {Binding Path=xyz}. Your Truck control could also set it's Canvas.Left/Top (if you chose to use a canvas in the pervious items control..or maybe it doesn't set its position at all if you made a custom panel for it) or a render transform as to put it at the correct X,Y. You could also use the items control in the truck's template to render out the cars in the same fashion you rendered out the trucks in the ferry control. Also its possible to create states for the VisualStateManager as to make it fully Blend supportable. So if a truck goes into a "problem state" you could easily style that state in blend to make it blink red, for instance.
I know it sounds like a lot to digest, but in the end having stylable controls all supporting an MVVM model will make your life 1000000x easier.
I'd suggest studying Microsoft's silverlight toolkit to get a good idea how to do lookless controls and such. Try looking at a simple control, like the DatePicker ( http://silverlight.codeplex.com/SourceControl/changeset/view/25992# ) One caveat is ignore DatePicker.xaml file (it's just a mirror of what gets put in generic.xaml and nothing bad would happen if you just deleted it).
The things you should pay close attention to are:
1.) The attributes on the class. These help Blend know how to deal with your control.
2.) The OnApplyTemplate override. This is where you can pull out specific elements from your template. These are known as "parts" and you will see the parts tab in Blend. The attributes in #1 can define what "parts" are in the template and what type they are expected to be.
3.) The DefaultStyleKey = typeof(...) in the constructor. This tells Silverlight what default template to use in the generic.xaml
4.) Look at Themes\generic.xaml. This is a special hardcoded file location that stores all your default templates. Search for the DatePicker style and you will get the idea :)
Good luck!
I just wanted to let you know, how I actually implemented it. It turned out that it was not necessary at all, to write custom controls or UserControls for this. All I did, was writing datatemplates for the car, ship, ferry, truck etc ViewModels. For example the datatemplate for the FerryViewModel contained an ItemsControl with a ItemsPanel of type Canvas (to be able to position the trucks) and an ItemTemplate that was a DataTemplate for TruckViewModel. A very simple and fast approach.
I'd suggest having one user control handle all the drawing. Otherwise you can get lost the the hierarchy of objects. Also it makes it easier if another item was added, say people in cars, trucks and ferries.
If your model is hierarchical then you can just pass in the top level into the control, and let the control sort itself out.
MVVM works well for existing controls, but existing WPF controls only work if there's a control that's close to what you need, and with a few tweaks would work. I can't think of a standard control in WPF that's close to what you need, so it's time to write a new control.
WPF works really really well with view models. If you can keep code behind away until specifically needed then you can separate ui from data so much more easily. It will allow your ui's to be some much more upgradeable if the data model doesn't change between different display.

Resources