What's the thought behind Children and Controls properties in WPF? - wpf

I don't know if this should go on Programmers, but I thought it was relevant here.
Being a skilled WPF programmer myself, I often wonder what people were thinking when they designed WPF in terms of naming conventions.
Why would you sometimes have a property called Children for accessing the children of the control, and then sometimes have an equivalent property, just called Controls instead? What were they thinking here?
Another example is the Popup control. Instead of a Content property, it has a Child property. Why would you do that? To me that's just confusing.
So I'm wondering if there's a logical reason for it, which would probably also help me understand what the properties are called next time I need to do some speed-programming.
If there's no reason behind it, then all I can say is WAT.

I've never seen a Controls property; as for Child versus Content: Content can be any object, data for example, whereas a Child has to be some FrameworkElement in the hierarchy of the controls. To me that makes perfect sense.

Related

How to initialize a view model with properties from another view Model

My question is what is the ideal way to initialize child window in WPF, MVVM way?
I have a WPF window , let's call it as ParentWindow having its view Model class - ParentWindowViewModel. On click of a button on the ParentWindow UI , I launch a new WPF window - ChildWindow like below
ChildWindow r = new ChildWindow ();
r.ShowDialog();
r.WindowStartupLocation = WindowStartupLocation.CenterScreen;
Now, the ChildWindow has its own viewModel like - ChildWindowViewModel. The Child Window has the datacontext set in its xaml as
<Window.DataContext>
<viewModel:ChildWindowViewModel/>
</Window.DataContext>
On Click of button in the ParentWindow, When i Launch the Child Window, I need to pass certain values to the Child Window, which will be used to initialize the Child Window. Without these values the child window cannot be initialized.Every time I click the button to Launch the child window, the values being passed to child window will differ based on some other selected items in the Parent Window.
I would do something like this (without error checking):
in ParentWindow.xaml.cs
private void Some_Event_In_Parent_Window()
{
ParentWindowViewModel pvm = DataContext as ParentWindowViewModel;
ChildWindow cw = new ChildWindow(pvm.Element1, pvm.Element2);
}
int ChildWindow.xaml.cs
public ChildWindow(bool elem1, string elem2)
{
InitializeComponents();
DataContext = new ChildWindowViewModel(elem1, elem2);
}
If you are dealing with minimal elements that need to be transferred between windows/VM's, and it is mainly about sending some form of "state" or "value", then there isnt too much issue with initializing the Viewmodel in the code behind. Remember that the <viewmodel:ChildWindowViewModel/> is equivalent to DataContext = new ChildWindowViewModel() in your code behind. While yes, you can create spaghetti code, or confusing dependencies by not adhering to patterns; you can also over engineer the crap of something that did not require the effort and can be just as confusing.
I find that there is an obsession with keeping your code behind empty (i have the same obsession). Remember, that the Code behind is there for a reason, and you CAN use it. Sometimes it isnt worth over-complicating your code base by implementing some big pattern if you have a single one off requirement that can be handled in code behind with some added comments.
Aside from Event Handlers, I utilize the Code Behind for these main use cases:
There is an adjustment needed to the UI that is too complicated to handle in the XAML alone. Example: I need a weird string concatenation and logic of some inputted text fields.
There is some minimal state or data needed to be transferred between Views. (Like your requirement)
There is some sort of logic that needs to happen that is UI specific and not related to the underlying data or ViewModel. (This is rare, and almost always a small one off).
In terms of "is this ideal" for MVVM; it depends on your definition of ideal.
Can this be handled by some other design pattern? Probably...? But is it worth it.
Does implementing said pattern add bloat or overhead that only solves a small problem? Maybe. That is for you to decide.
Are you going to be repeating this implementation more than once? If so you may have some bad design to rethink.
Does implementing this solution of using Code behind solve your issue in a speedy way, that is moderately maintainable and readable? If so, then I wouldnt see a problem.
Ideal is not always defined by rules. It is also specific to your needs and requirements.
It isnt always easy to determine where your use case should be handled. View, ViewModel, maybe a Service, or a Singleton state class.
If your use case is this one window, Code behind is fine (In my opinion). If you are doing this for 20 windows, you may want a Service to maintain the state somehow. Think of it more - if your code is SOLID and DRY

Is it wrong to access TreeViewItems in WPF’s TreeView?

I’ve been having issues with the TreeView in WPF. This control makes it very hard to access the TreeViewItems it’s showing.
On several occasions I have worked around the need to access a TreeViewItem, for example I’ve accepted the fact that I’m not supposed to access a node’s parent via TreeView (and am supposed to instead keep track of the parent myself). I’ve been doing this for two reasons: first, it’s obviously extremely hard to get at the TreeViewItems, and secondly, I’ve been told that it’s hard because I’m not supposed to need them if I do things right.
However, this time I really see no way around this.
Basically, all I want is, given one of my viewmodel instances, scroll the tree view to it. This is trivial if I could just get the corresponding TreeViewItem.
Am I doing things wrong again by trying to get at the TreeViewItem, or would that be the right approach?
Take a look at Simplifying the WPF TreeView by Using the ViewModel Pattern article by Josh Smith. I hope it helps.
Admittedly this is not straightforward but you can probably still do this while keeping a separation which does not require you to access the TreeViewItems knowingly. The essence in WPF is binding as already noted by Kent Boogaart in your other question, here however you need to somehow deal with events. Your view-model needs to fire a BringIntoView event of its own while the view needs to react.
The easiest method might be to add a EventSetter on Loaded to make the TreeViewItems subscribe to said event on their DataContext which should be your view-model (if it isn't you can wait for DataContextChanged).
No, I dont see in what way accessing the items of a treeview is wrong.
I think the difficulties you are encountering are because you aren't seeing the treeview as it should be.
A leaf has a parent, but no children.
A node can have a parent, and can have children.
A node without a parent is a root.
Based on these principles (SourceMaking Composite pattern) you should be able to do whatever you want using recursivity. (in both XAML and code)
I’ve come to the conclusion that it can’t be altogether wrong. The first piece of evidence comes from Bea Stollnitz’s post about ListView: if one of the WPF developers explains how this might be done, it can’t be that wrong.
The other piece of evidence comes from this highly-voted question/answer: MVVM madness. MVVM undoubtedly has its benefits, but sometimes the cost of following MVVM is so high that it’s just silly following through with it, especially in a small one-man application. Do you really want to expose IsSelected and IsExpanded the way you’re supposed to?
As a result, I felt justified to try and figure out how to expose the TreeViewItem corresponding to an item with less effort from the developer, under the assumption that they will never need the more advanced features that resulted in TreeViewItems being this hard to access (like displaying the same ViewModels in multiple different controls... how often have you needed that!...)
I posted the result of this effort as an answer on another question.

Custom property dependant on other properties

Advance apologies for the event-style explanation; there's a lot of factors that I feel all play a role of their own. WPF is not my native framework of choice, and it probably shows. :)
Old situation: I had a window with several controls. Depending on their selections, I used multibindings and a converter to determine whether certain controls needed to be shown that inform the user about the implications of their changes before they'd eventually confirm them by OK (or simply dismissed by using Cancel). This worked perfectly.
Problem: Too many controls as time went by, too much clutter.
Solution: Put stuff in different Pages so it becomes easier to browse for the user. In order to have changes-to-be persist as a user arbitrarily browses between the pages, I create these dynamically and put them in a cache (Dictionary<string, BasePage>, see below), from which they will be pulled as the user chooses them.
Consequence: I need to decouple the bindings to the notification controls as the different options are now on different pages.
Solution? I put a BasePage class in that exposes certain abstract read-only properties that define the various aspects that the window needs to know about in order to do its notifications. For example, a bool requiresReboot property defines whether the current state of things on that page requires a reboot to take (full) effect. A specific page implements the property based on its controls.
Problem: I do not know how to keep create a proper binding that properly gets updated as the pages are changed. I tried giving my notification controls a binding to the Dictionary<string, BasePage> with a converter that checks all pages and the relevant property.
Questions:
1) How do I create a proper property for this purpose? I presume I need a DependancyProperty as I did a fair bit of reading on MSDN, but I can't figure out how this fits together.
2) How do I make a link between my custom property so that it allows (multiple) control(s) on a page to change that property? Do I use INotifyPropertyChanged somehow? My old example bound against several CheckBox.IsChecked properties in XAML. I am trying to avoid putting tons of events (OnChange, etc) on the controls as the original code did not need it and I have been told it makes for a messy solution for as far WPF is concerned.
3) Finally, I suspect I may need to change my Dictionary<string, BasePage> class to a custom implementation that implements some sort of INotifyPropertyChanged but for Collections? Observable Collection is the term I am looking for, I believe.
I hope someone is able to bridge the gap in my understanding of WPF (property) internals; I would very much appreciate it. A basic sample would be even better, but if it is too complicated, just a nudge in the right direction will do. Thank you. :)
It's been a while since I solved this, and while I cannot remember the exact cause of the problems, there were a few different issues that made up the bulk of the trouble I ran into.
I ended up making the Property in question a non-abstract DependencyProperty in the base class; it was the only way in which I could properly delegate the change notifications to the interface. Derived classes simply ended up binding it to their controls (with a proper Converter in the case extra logic was necessitated).
As Dictionary<string, BasePage> does not support any sort of change notification, I made an extra collection of ObservableCollection<BasePage> which I used for binding purposes.
However, such a collection does not propagate a change event when items inside of it has a property changed. Since this situation required that, and I was binding to the collection itself in the context of a property that does not have a Master<->Detail relationship like a DataGrid (which basically add their own OnPropertyChanged handlers to the binded object), I ended up subclassing a VeryObservableCollecton<>. This one listens to its own items, and throws a proper change event (I think it was an OnPropertyChanged from the INotifyPropertyChanged interface) so that the binding (or in this case a multi-binding) would refresh properly and allow my interface to update.
It is hardly the prettiest code, and it feels over-engineered, but at least it allows me to properly bind the UI to the data in this manner.

Pros and cons of having a WPF specifics in the view model

I'm having trouble deciding what to think about this piece of code:
public SolidColorBrush Brush
{
get { return IsValid ? _validItemBrush : _invalidItemBrush; }
}
It is part of a view model in my current project and as you can imagine, the Brush will be bound to some text elements in the UI, to indicate (in-)validity of other pieces of data, in an otherwise fairly simple and straightforward dialog.
The proponents of this piece of code say that since we're using WPF, we might as well allow for some simple WPF specific constructs in the view model.
The opponents say that this violates Separation of Concerns, as it clearly dictates style which should be taken care of solely by the view.
Please share your arguments, and if you're not happy with the code above, please share your ideas around alternative solutions. (I'm particularly interested in what you have to say about using DataTemplates).
Is it possible that there is one solution that could be considered best practice?
Personally, I would have the two brushes be defined in XAML, and have the controls that use them switch brushes (in xaml) based on the IsValid property. This could be done very easily with DataTriggers, or even a single IValueConverter - the converter could take 2 brushes and a boolean and swap between them fairly easily.
This keeps the business logic presentation-neutral - a "Brush" is very specific to a specific form of presentation, and a pure View choice. Hard-coding this into the ViewModel violates the single responsibility principle as well as is not a clean separation of concerns.
I would very much keep this in the View, and switch based on the IsValid (bound) property that is ViewModel specific.
While there are circumstances where I might use WPF constructs in the view model, this isn't one of them. Here's why:
It's harder to change. If you define brushes as resources and use them in styles, changing your application's color scheme can simply be a matter of loading a different resource dictionary. If you hard-code color values in your view models, you have a lot of different things to change if it turns out your end users need different colors.
It's harder to test. If you want to write a unit test that checks to see if a property is returning the right brush, you have to create a brush in your unit test and compare the values of the two, since it's a reference type.
In many, maybe even most cases, it doesn't make the code simpler or easier to maintain. You're pretty likely to already be using a style (assuming that you are conversant with styles), since they make just about everything in WPF easier. Binding IsValid to brush colors is just a matter of adding a DataTrigger to a style. Which is where anyone maintaining this code would expect to find it.
There are certainly times when I do use WPF constructs in the view model - for instance, long ago stopped wondering if it was problem if a view model exposed a property of type Visibility. Note that none of the above concerns apply to that case.
In cases like yours where it's purely aesthetic I use Triggers or the Visual State Manager to change colors.
Sometimes I do use colors in my ViewModels, but only if its part of my software spec (e.g., the color of the chart displaying a patient's CO2 depends on localization). In that case, I use a Color struct bound property, allowing the View to use the Color for a SolidColorBrush, a GradientStop, or whatever it wants. I initially used a string in #AARRGGBB format to completely remove the WPF dependency but my more seasoned co-workers didn't like that.

What's the "right" way to isolate control dependencies

I've made it a personal rule to inherit every UI control before using it. In a previous life I'd always considered this one of the less useful things you could do because the justification always seemed to be "I might want to change the font on all the buttons at once"... a motivation that never paid off... once... ever.
Two recent projects have changed my mind about the practice, though. In the first, we needed a consistent "ValueChanged" event so that we could easily implement a "dirty" flag on our forms without a massive switch statement to choose between a Textbox's "TextChanged" event, or a ListBox's "SelectedIndexChanged" etc. We just wanted one consistent thing to listen for on all controls, and subclassing the built-in controls bought us that pretty easily.
In the second project, every effort was made to get by with the base controls because the UI was expected to be pretty simple, but a few months in, it became obvious that they just weren't going to cut it anymore, and we purchased the Telerik control suite. If we had inherited all the controls to begin with, then changing our derived controls to inherit from the Telerik controls would have applied the changes for us globally. Instead, we had to do some searching and replacing in all the form designers.
So here's my question: What are the relative strengths and weaknesses of
Simply adding a Class, and making it inherit from a control.
Adding a new "Custom Control" and inheriting.
Adding a new "Component" and inheriting.
All three have the same effect in the end, you get a new type of Button to put on your forms. I've seen all three used by different people, and everyone seems to think that their way is the best. I thought I should put this discussion on StackOverflow, and maybe we can nail down a concensus as a community as to which one is the "right" way.
Note: I already have my personal opinion of which is "right", but I want to see what the world thinks.
If both 1 & 2 are inheriting, then they are functionally identical, no? Should one of them be encapsulating a control? In which case you have a lot of pass-thru members to add. I wouldn't recommend it.
Peronally, I simply wouldn't add extra inheritance without a very good reason... for example, the "changed event" could perhaps have been handled with some overloads etc. With C# 3.0 this gets even cleaner thanks to extension methods - i.e. you can have things like:
public static AddChangeHandler(
this TextBox textbox, EventHandler handler) {
testbox.TextChanged += handler;
}
public static AddChangeHandler(
this SomethingElse control, EventHandler handler) {
control.Whatever += handler;
}
and just use myControl.AddChangeHandler(handler); (relying on the static type of myControl to resolve the appropriate extension method).
Of course, you could take a step back and listen to events on your own model, not the UI - let the UI update the model in a basic way, and have logic in your own object model (that has nothing to do with controls).
I use composition. I simply create a new UserControl and add the controls I need. This works fine, because:
I never use that many properties anyway, so pass-through methods are kept to a minimum.
I can start with a naive approach and refine it later.
Properties for look and feel should be set consistently across the site. Now I can set them once and for all.

Resources