Hide Elements in WPF TreeView - wpf

i have the following scenario:
I have a ViewModel with hierachical elements to display in a TreeView. So far so good. What i want to do now is hide/remove elements from the TreeView according to some property set on a ViewModel-Element, like IsConfigurable or such.
If i disable die DataTemplate, the element is removed, but also all child-elements, which is not what i want.
Is that even possible?
Greets,
Jürgen

That sounds somewhat strange, but nevertheless...
You should consider that your application shall remain test and debuggable.
Your model contains the orginal data (collection) as it is - no meddling here. In your ViewModel, the object that you are binding to, you can calculate the transformation as you want to display your hierarchy. This approach has the benefit, that you can "easily" test/debug your transformation. Now bind your TreeView to the calculated hierarchy without obscure experiments. If properties in your ViewModel (you mentioned IsConfigurable or whatever) change, you know when to re-calc your bound hierarchy.

Related

Is it correct to let the viewmodel add children to its view?

Im currently learning about the MVVM pattern in WPF. I think it is really cool but my question is: is it correct to use the viewmodel directly for appending children to its view?
For example lets assume we had a method which contains a loop which adds new rows to a grid when a button is clicked. Should my ViewModel only contain pure data or can it also contain logic for placing new elements on the field? As well as removing them.
is it correct to use the viewmodel directly for appending children to its view?
No. The view model shouldn't know about any view elements.
Should my ViewModel only contain pure data or can it also contain logic for placing new elements on the field? As well as removing them.
The former. The view model may expose a collection of data objects that the view happens to display in a Grid. Or some other kind of panel. The view model doesn't care about which.
You would typically use an ItemsControl in the view to display the items in a view model collection, i.e. the ItemsControl binds to the source collection and displays a visual representation of each item in a panel.

ListBox on Canvas: overlay multiple canvases or use CompositeCollection?

In wpf with mvvm I use a ListBox with Canvas as ItemsPanelTemplate and DataTemplates to customize appearance.
I would like to improve performance by first adding all items of type 1 to the drawing, then all items of type 2.
I could create two ListBoxes both with Canvas as ItemsPanelTemplate and they would be overlays.
Panning and scrolling could be synchronized by means of bindings.
This way I can raise PropertyChanges for both lists independantly from each other.
Question: do you have experience whether overlaying canvases is good or bad for performance?
I an not sure whether this is also possible using a CompositeCollection for the ItemsSource of one ListBox. Or for that matter give both types a common subclass and stay with ObservableCollection.
Question: do you think that somehow a list with CompositeCollection can be given separate PropertyChanges for different parts of the Collection?
EDIT:
Suppose I have a great number of points, lines, labels for the canvas, each of a different type, however with a common base type. I select the DataTemplate using DataType: DataType="{x:Type my:Point}", DataType="{x:Type my:Line}" etc.
First as quicly as possible I want the user to see the lines. I raise PropertyChanged("Lines") and the ListBox+Canvas for the lines is visible.
In a backgroundworker I raise PropertyChanged("Points") and the ListBox2+Canvas2 for the points is visible.
When done in another backgroundworker I raise PropertyChanged("Labels") and the ListBox3+Canvas3 for the labels is visible.
There's a much simpler solution using basic Object Oriented Programming. Create a base data type and make all of your data objects extend from it. It could be empty, but if nothing else, you could implement INotifyPropertyChanged in it so you don't have to in each of the other data types.
Then you simply add a property of type ObservableCollection<BaseClass> to your view model or code behind and data bind that to the ListBox.ItemsSource property. As long as you don't set the x:Key values on the different DataTemplates, then WPF will implicitly set them to the relevant data type objects when it renders them.
So you can put all of your different data types in the same collection. Then you can add your first type in and wait for however long and add some of a different type, or whatever order you feel like.
UPDATE >>>
In response to the edit in your question, I don't quite understand the reason for you trying to use the INotifyPropertyChanged interface to show the items, type by type. If you have the base class collection that I mentioned above, then you simply add the instances of the first type to the collection first, so they'll appear first. When you want the next type to appear, just add them into the collection and then they'll appear and so on. The ObservableCollection will take care of that.

wpf - bind label widths to calculated length property

If I had a label on a view that I wanted to have the width equal to the width of two columns in one of my grids on the same view, how would I set up the binding without using a converter? Should I use properties to preform my calculation and store a value? It is my intention that if the view's grid size changes then this label's size will also change to match the new width of the two columns.
And where should I put this logic? I am trying to follow MVVM pattern but I see that a lot of threads about "converters in MVVM" say to put the logic into the viewmodel.
I tried to implement this behavior with dependency properties on my view since my viewmodel technically has no knowledge of my view (so how would my viewmodel know how wide my columns currently are?). This goes against what I have read online though. When implementing this behavior I noticed that I cannot reference my columns by name unless my property is not static, but dependency properties are static so I am not sure how to shuffle my values around without creating yet more properties to hold values.
Can someone provide help here? I feel like i'm overcomplicating this. I just need this label to sit over these two columns however they stretch. It just provides a visual grouping of related fields in the grid. Once I can do this first one, the other two should be equally similar.
My rule of thumb is if it's "View" related then keep it away from the ViewModel. From your description this sounds like it's purely view related, so I would just use logic in either the codebehind or a converter.
Now what I don't understand is why you are reluctant to use Converters. With converters you certainly don't want to store business logic that is going to lead to confusion or pain points for refactoring, but if you have some value that needs to be converted for a specific view operation then Converters are exactly what you should be using.
So my advice is Converters ... if it's View related then feel free to use Converters and Codebehind ... in fact you should use them and not the ViewModel.
Does that help?

Access Elements inside a DataTemplate... How to for more than 1 DataTemplate?

I've got 2 DataTemplates defined for a Listbox Control. 1 Template is for the UnSelected State and the other one is for the Selected State(showing more detail than the UnSelected State).
I followed the example here:
Link
about how to access the Elements inside the DataTemplates from Code behind.
I get it right, but it only finds and returns an element of the UnSelected DataTemplate. But when i search for an element in the Selected DataTemplate i get a NullReferenceException.
What could i be doing wrong?
Setting keyboard focus might be one reason you need to access the datatemplate elements. MVVM will not solve that issue and the FocusManager doesn't set keyboard focus.
What you are doing wrong?
I would say what you are doing wrong is trying to access elements inside the DataTemplate from code-behind. Naughty, naughty!
All joking aside, 99.9% of the time I see someone trying to access an element inside a DataTemplate from code, it is because their application is poorly designed, with no (or few) bindings and no view model at all. Many beginners tend to store their data directly in UI elements rather than using a view model. I think it is because their minds have been corrupted by experience VB, WinForms, and ASP.NET where it was the "normal" way to do it. There are a thousand reasons to use a view model and bind your data instead of storing them in UI elements. Look up "model view view model" online for more details.
Now to answer your question:
Any given ListBoxItem can only have one DataTemplate at a time. This is because its ContentPresenter has only one ContentTemplate property, and this property cannot have two different values.
Because of this, the visual tree under a ListBoxItem will always be generated from one a specific template, not a combination of several templates. If you change the ItemTemplate of the ListBox or otherwise update ListBoxItem.ContentTemplate, the visual tree produced by the old template will be thrown away and a new one built.
Let me say that again: If you change data templates, the visual tree produced by the old data template will be thrown away and a new visual tree built.
You can have a hundred data templates defined and usable on a given ListBoxItem, but only one at a time can have a visual tree instantiated for it. And these are the only elements that actually exist as part of the visual tree. All other templates exist only as templates - there are no actual elements created for them.
To put it another way: It is meaningless to ask about how to find elements in two different visual trees instantiated by two different templates on the same control, because a single control cannot have two different templates active at the same time.
Hope this clears things up for you.
Final advice: Do read up on MVVM, and stop trying to access elements inside DataTemplates ASAP. However if you think you might be in that 0.1% who actually do have valid reasons to access elements inside templates, write back with your actual reason for wanting to do so and maybe I can provide further guidance.

WPF CollectionViewSource in Custom Control misuse?

Should you use CollectionViewSource in the WPF Custom Control's code behind?
I'am asking because the CollectionViewSource.GetDefaultView(SOURCE) with .Filter set
changes the view so that all instances of the Control have the same view.
Doesn't it mean, that in the Custom Control's code behind, you should avoid use of CollectionViewSource ?
It depends on the desired behavior. E.g. if you had multiple lists of states on the screen and wanted to filter all of them by region at the same time, then this could be desired behavior. You can always force a different view source in cases where you do not want the items bound to the same filter criteria.
I think avoiding the use of CollectionViewSource until you understand the interactions of ItemsSource -> CollectionView -> Bound Item controls is probably a good idea, but I don't know that I would go so far as to say that you should avoid it in general.
I think it might be reasonable to say that if two lists on a form have different filtering/sorting requirements then they should be bound from different source properties (even if those properties are straight clones of a single underlying source). That way you can still apply filtering and storing at the CollectionViewSource level but without unintended consequences later on.

Resources