How do I determine AncestorLevel for RelativeSource in WPF? - wpf

In a WPF application using a fairly standard MVVM pattern, I need to bind from a row in a DataTable (i.e. deep inside the visual tree) to the data context of the whole window. I am assuming the only way to do this is to use Mode=RelativeSource, but it requires that I specify the AncestorLevel.
How do I determine the AncestorLevel?
Why should I need to specify this at all when I know there is only ever one window? In other words, why can't I simply specify the type I want to bind to and have the binding engine reverse up the tree until it finds the first object of the required type?
If I do figure out the AncestorLevel, doesn't this make the code brittle? (If I change the nesting of the visual elements, it will obviously break.)
If there is no good solution involving RelativeSource, I thought I could take an alternative approach and 'propagate' the page-level property down through the logical tree to the individual items in the list. Is there an accepted pattern for this?
Has RelativeSource ever had a way of traversing up the tree searching only by type (or am I imagining this)?

See my question, similar issue was raised there:
WPF finding ancestor for binding
In short - when you give the ancestor type, it is searched upwards the elements tree until the ancestor of that given type is found (Level 1). Should you need to search two levels up (e.g. you have a grid in a grid and you're aiming for the "outer" grid), you specify AncestorLevel=2 and the ancestor is then a second element of that particular type while traversing the elements tree.

How do I determine the AncestorLevel?
By looking at the visual tree and figuring out the number of occurances of a specific type of parent element. There can only be only one top-level parent window though.
Why should I need to specify this at all when I know there is only ever one window?
You don't have to. It's perfectly fine and also very common to only specify the AncestorType like this:
{Binding SomePropertyOfTheWindow, RelativeSource={RelativeSource AncestorType=Window}}" />
If I do figure out the AncestorLevel, doesn't this make the code brittle? (If I change the nesting of the visual elements, it will obviously break.)
Yes, this is correct, but this is how you tell the binding engine to which particular item of a specific type that you want to bind to - assuming there are several to choose from.

Although this is not binding to a Relative source, but another way of binding without the complexities of Relative and type.
Another option instead of binding to a specific type of control, you can name your controls in the xaml with x:Name. Then you can bind directly to that control and property on it. Ex:
<SomeControl x:Name="IWantThisControl" />
[bunch of other controls]
<YourOtherControl ThisControlProperty={Binding ElementName=IWantThisControl, Path=PropertyOnTheOtherControl}" />
It does not matter the nesting level of the controls when you use the binding to ElementName reference.

Related

How can I Improve performance of RelativeSource FindAncestor?

Is FindAncestor searches an element in whole Visual tree of Window?
If yes, then how can I improve on it ??
Is binding data error thrown if we access property of object by finding an element with Find Ancestor & no such a element exist?
If yes, then how can I resolve such a error.
In my case binding error is throwing on output window. To solve this error, I tried with setting FallbackValue,but now it gives me warning instead of error that is the only difference. Everything else is same as error.
Can someone tell me How exactly FindAncestor works??
If you want to know how FindAncestor works internally, you should read the internal code. http://referencesource.microsoft.com/#PresentationFramework/Framework/MS/Internal/Data/ObjectRef.cs,6a2d9d6630cad93d
You should try and not use FindAncestor that much. It can be slow, plus the children shouldn't rely on the knownledge of "there exist somewhere a parent who has what I need".
That said, FindAncestor itself can be also your friend at times.
It depends on your case, but for example, it's common to have a DataGridRow which uses FindAncestor in order to find information about DataGrid or some other parent element.
The problem with that is: IT'S SUPER SLOW. Say you have 1000 DataGridRows, and each row uses FindAncestor, plus each row has 7 columns, which itself has to traverse through ~200 elements in logical tree. It does not have to be slow, DataGridRow has always the same parent DataGrid, it can be easily cached. Perhaps "One-time cached relativeSources" would be the new concept.
The concept can be like this: write your own relativeSource binding as you've done. Once the binding is done first time, use visual tree helper to find a parent of specific type. If that is done, you can store the found parent IN the direct parent attachewd property, as so:
var dic = myElementThatUsesRelativeSourceBinding.Parent.
GetCurrentValue(MyCachedRelativeSourceParentsProperty)
as Dictionary<Type, UIElement>;
dic[foundType] = actualValue;
Later, you use this cache information in the search of relative source later. Instead of taking O(n), it will take O(1) for the same element / children of parent.
If you know that the parent always exists, you should create the binding in code-behind, for each element that tries to use FindAncestor. This way you avoid traversing the tree.
You could also create a hybrid solution which tracks the changes of visual tree, and mainains "cache". If a DataGridRow asks for "find me relative source off type DataGrid", there is no reason that you need to do it all the time: you could cache it. There's OnVisualChildrenChanged - just an idea, not even 100% sure if it can be done nicely, but this will require extra memory, and dictionary.
This can get very complex, needless to say :-), but would be cool for "side project".
On another side; you should also flatten visual tree, it would gain you a speed.
When using the FindAncestor value of the RelativeSourceMode Enumeration for the RelativeSource.Mode Property, you can also set the level of ancestor to look for using the RelativeSource.AncestorLevel Property. From the last linked page:
Use [a value of] 1 to indicate the one nearest to the binding target element.
There is not much to tell about "Find Ancestor". It works simple which is why its fast. It works like this: The type of the parent of an element is always being asked. If the type does not match with one you need. The parent becomes actual element and the process is being repeated again. Which is why "Find Ancestor" always works the visual tree up but never down :)
The only possible reason where I think you might feel some performance issues with RelativeSource bindings is when you in ListBox and you have really a nasty item template defined with a bunch of RelativeSource bindings inside. ListBox tends to virtualize stuff that means it keeps track of data items but recreates their containers. To sum up, you start scrolling and the faster you scroll the more often are those visual containers gonna be recreated. In the end everytime a container gets recreated the relative source binding will try seek for given ancestor type. That is the only case that I can think of right now where you will end up lagging few milliseconds. But that is not bad..
Are you experiencing some kind of issue like this? Tell us more about your issue please
Like Sheridan I would let those erros just be :) however if you hate them that much, you could work with bridges
A Bridge is something you will need to implement yourself.
Take a look at this link: http://social.technet.microsoft.com/wiki/contents/articles/12355.wpfhowto-avoid-binding-error-when-removing-a-datagrid-row-with-relativesource-static-bridgerelay.aspx
Basically you put that bridge element somewhere in your Xaml as a resource and when you need RelativeSource you use StaticResource extension instead like this:
Binding="{Binding MyPath, Source={StaticResource MyBridge}}"
Try it out

How to change element in xaml that are in visual tree

I'm new to WPF and tyring to uderstand the best way I can modify any given control attributes. What I was trying to achieve is to show tooltip for a cell. Yes a quick google and can see xaml of how to do it. But I want to understand how can one learn to figure out this out using some tool.
I came across Snoop that can show visual tree of a control very easily (CTRL+SHIFT Mouse over). What I'm trying to understand is if one knows of visual tree, how can one change it? For example, let's say I use WPF DataGrid and bind it to a source and display column using DataGridTextColumn.
<DataGridTextColumn Header="First Name" Binding="{Binding FirstName}">
Now let's say I want to show tooltip for each cell. So I fire up Snoop and CTRL+SHIFT mouse over the cell. Snoop shows me that its a DataGridCell that is using Border and withing it ContentPresenter which ends up using TextBlock to show the value. So that means that if I can somehow access that textblock, I can set its tooltip property using binding. Issue is that I don't know how I can access it in xaml.
In other words, knowing a visual tree, how can one access it in xaml for any given control. This will also be very handly for 3rd party controls.
Thanks
Your'e asking quite a bit here, and i'm not sure I completely understand your intention, so I hope I got this right. Your'e asking if you can access the complete visual representation of each control and change it using xaml. The answer to that is yes, but you shouldn't.
I'll get to what I mean in a bit, but first I'd like to clarify some concepts, since i'm not sure you're using them correctly.
XAML:
Xaml is the declarative markup representation of your views and nothing more. Xaml syntax directly corresponds to it's respective classes and their properties. Xaml maps tags to classes and attributes to properties. It's a small distinction, but it's important to think this way. Everything you can do in xaml you can also do in code (although it would often be much more work). Again: xaml refers to markup code only.
<ClassA PropertyA="Value">
<ClassA.PropertyB>
<ClassB />
</ClassA.PropertyB>
Default property value
</ClassA>
Logical tree:
The logical tree is the runtime representation of your xaml code. it consists (mostly) of the controls you set in your xaml files.
Visual tree:
The visual tree is the visual representation the logical tree. It contains much more since it contains the concrete visual representation of everything displayed in your view. Most of the logical tree can't be directly displayed. WPF uses Data and Control Templates together with Styles to determine exactly how each object is supposed to look. In case of data templates that can also mean simple data objects and not only WPF controls.
Now for your question: so can you access the concrete visual representation of each control?
Yes, but you'll have to use control templates to manipulate it's visuals. Also, control templates are usually applied to control types and not specific controls, so you'll have to deal with that as well.
And that's why you shouldn't access it. The xaml representation usually gives you all you need to modify your control, and even if you do use templates you shouldn't change every last piece of it. Templates are used to style a control, so only write enough to show it as you wish. There's no need specify everything.
However you can access the entire visual tree more easily using procedural code, if you use the VisualTreeHelper class (that's how snoop does it, by the way). Using it you can traverse the visual tree and access all it's classes and members. If you really want to access every single visual object you'll do it much more easily with the VisualTreeHelper.

How to access Parent's DataContext in Windows 8 store apps

This is a common situation in XAML based apps (WPF/Silverlight/WinRT).
WPF related link -> WPF Databinding: How do I access the "parent" data context?
RelativeSource with AncestorType, and Mode=FindAncestor usually comes to rescue in WPF.
Both of these are missing in WinRT API. How to access the Parent's (may not be immediate one), DataContext?
(I am aware of TemplateBinding, and ElementBinding but both are not suitable mostly in DataTemplate).
I just had the same problem. Presumably this is common??
Here is a crude solution that works:
Bind the Tag property of a top level element to the DataContext
<Grid Name="gridTop" Tag="{Binding}" />
Bind the property you want via ElementName in nested element, ie
{Binding Tag.SomeProp, ElementName=gridTop}
ElementName binding is still possible and might work in your case. Otherwise you'd need to implement an attached behavior.
There are several ways you can deal with this issue:
ElementName binding is the most common approach, as Filip pointed out.
You could walk visual tree till you find the parent. That is what FindAcestor does internally. You could dress it up in behavior for easy reuse.
If you use view models you could use messages instead of bindings or you could add parent context to each child view model.
Picking the best solution will depend on your specific circumstances.

Hide Elements in WPF TreeView

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.

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.

Resources