How is Storyboard.TargetName implemented? - silverlight

I'm creating a custom ToolTip that needs to get a reference to another control. It's very similar to how Storyboard.TargetName would work. Now I've rolled my own implementation on how to get the target reference such as (note that my target will always be a parent of the ToolTip):
public object FindTarget(string targetName)
{
var target = default(object);
FrameworkElement item = this;
while ((item = item.Parent as FrameworkElement) != null && target == null)
target = item.FindName(targetName);
return target;
}
My question is is there a way to do this that's built into the framework? It seems like this is a common enough task that it would be.
Edit:
Turns out the above algorithm doesn't actually work for ToolTips because their Parent property is always null. I'm assuming ToolTips are based on Popups and this is why the Parent is null.

You can use extension methods to make it visible from anywhere you want:
public static object GetElementByName(this FrameworkElement baseElement, string name)
{
object target = null;
FrameworkElement item = baseElement;
while ((item = item.Parent as FrameworkElement) != null && target == null)
target = item.FindName(name);
return target;
}
After this you are able to call this method on any FrameworkElement.
Although you should be aware of the fact that FindName will not work for names defined in Templates.

Related

Visual Tree Finder is returning null while searching for Data Grid

I have Tab Control which has many tab items, I am checking Data Grid Items Count while closing tab items. For the first time it works fine(I mean in first iteration). After closing one tab item, in second iteration sellDtg is null. Does anyone know why it is happening? I am concerning that this is UI problem, layout is not being refreshed. Please help me or show direction.
while (tc.HasItems)
{
TabItem ti = tc.SelectedItem as TabItem;
if (ti.Header == "Продажа")
{
Microsoft.Windows.Controls.DataGrid sellDtg = FindChild<Microsoft.Windows.Controls.DataGrid>(tc, "SellDataGrid");
if (sellDtg.Items.Count > 0)
{
Sell sl = new Sell();
if (Sell.basketfromSellDateListBox == false)
{
sl.ClearBasket(sellDtg);
Sell.ClearFromSellBasket((int)sellDtg.Tag);
}
}
}
if (ti != null)
tc.Items.Remove(ti);
}
Thanks in advance!!!
I've written a simple FindChildLogical function in analogy for LogicalTreeHelper below:
public static T FindChildLogical<T>(DependencyObject parent, string childName)
where T : DependencyObject
{
if (parent == null) return null;
var child = LogicalTreeHelper.FindLogicalNode(parent, childName);
return (T)child;
}
and you call it as:
Microsoft.Windows.Controls.DataGrid sellDtg = FindChildLogical<Microsoft.Windows.Controls.DataGrid>(ti, "SellDataGrid");
I hope it gets you where you intend to.
I am going to assume your FindChild method uses the VisualTreeHelper to find its children.
In the first iteration, the TabItem's Content has been through a layout pass, and is visible. This means that the TabItem's Content will be in the visual tree.
However, for the other tab items, their Content hasn't been through a layout pass (it is only added to the visual tree when it's parent gets selected, and this has to then go through a layout/render pass), and won't be in the visual tree.
There are a couple of ways to get the child content of a TabItem that hasn't been through a layout pass as the selected tab:
1) You can try using the LogicalTreeHelper to find the Grid you're looking for (and you will likely have to search the Content of the TabItem, not the TabControl).
2) You can take your code out of the while loop, and do a callback on the dispatcher at the Loaded priority:
void RemoveAllItems()
{
if (!tc.HasItems) return;
TabItem ti = tc.SelectedItem as TabItem;
if (ti.Header == "Продажа")
{
var sellDtg = FindChild<Microsoft.Windows.Controls.DataGrid>(tc, "SellDataGrid");
if (sellDtg.Items.Count > 0)
{
Sell sl = new Sell();
if (Sell.basketfromSellDateListBox == false)
{
sl.ClearBasket(sellDtg);
Sell.ClearFromSellBasket((int)sellDtg.Tag);
}
if (ti != null)
tc.Items.Remove(ti);
}
}
Dispatcher.BeginInvoke(new Action(RemoveAllItems), DispatcherPriority.Loaded);
}
If you use the second method, you will likely be able to see the tab items removed one at a time, which may be something you don't want to see.

ItemContainerGenerator.ContainerFromItem() returns null?

I'm having a bit of weird behavior that I can't seem to work out. When I iterate through the items in my ListBox.ItemsSource property, I can't seem to get the container? I'm expecting to see a ListBoxItem returned, but I only get null.
Any ideas?
Here's the bit of code I'm using:
this.lstResults.ItemsSource.ForEach(t =>
{
ListBoxItem lbi = this.lstResults.ItemContainerGenerator.ContainerFromItem(t) as ListBoxItem;
if (lbi != null)
{
this.AddToolTip(lbi);
}
});
The ItemsSource is currently set to a Dictionary and does contain a number of KVPs.
I found something that worked better for my case in this StackOverflow question:
Get row in datagrid
By putting in UpdateLayout and a ScrollIntoView calls before calling ContainerFromItem or ContainerFromIndex, you cause that part of the DataGrid to be realized which makes it possible for it return a value for ContainerFromItem/ContainerFromIndex:
dataGrid.UpdateLayout();
dataGrid.ScrollIntoView(dataGrid.Items[index]);
var row = (DataGridRow)dataGrid.ItemContainerGenerator.ContainerFromIndex(index);
If you don't want the current location in the DataGrid to change, this probably isn't a good solution for you but if that's OK, it works without having to turn off virtualizing.
Finally sorted out the problem... By adding VirtualizingStackPanel.IsVirtualizing="False" into my XAML, everything now works as expected.
On the downside, I miss out on all the performance benefitst of the virtualization, so I changed my load routing to async and added a "spinner" into my listbox while it loads...
object viewItem = list.ItemContainerGenerator.ContainerFromItem(item);
if (viewItem == null)
{
list.UpdateLayout();
viewItem = list.ItemContainerGenerator.ContainerFromItem(item);
Debug.Assert(viewItem != null, "list.ItemContainerGenerator.ContainerFromItem(item) is null, even after UpdateLayout");
}
Step through the code with the debugger and see if there is actually nothing retured or if the as-cast is just wrong and thus turns it to null (you could just use a normal cast to get a proper exception).
One problem that frequently occurs is that when an ItemsControl is virtualizing for most of the items no container will exist at any point in time.
Also i would not recommend dealing with the item containers directly but rather binding properties and subscribing to events (via the ItemsControl.ItemContainerStyle).
Use this subscription:
TheListBox.ItemContainerGenerator.StatusChanged += (sender, e) =>
{
TheListBox.Dispatcher.Invoke(() =>
{
var TheOne = TheListBox.ItemContainerGenerator.ContainerFromIndex(0);
if (TheOne != null)
// Use The One
});
};
I'm a bit late for the party but here's another solution that's fail-proof in my case,
After trying many solutions suggesting to add IsExpanded and IsSelected to underlying object and binding to them in TreeViewItem style, while this mostly works in some case it still fails ...
Note: my objective was to write a mini/custom Explorer-like view where when I click a folder in the right pane it gets selected on the TreeView, just like in Explorer.
private void ListViewItem_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
var item = sender as ListViewItem;
var node = item?.Content as DirectoryNode;
if (node == null) return;
var nodes = (IEnumerable<DirectoryNode>)TreeView.ItemsSource;
if (nodes == null) return;
var queue = new Stack<Node>();
queue.Push(node);
var parent = node.Parent;
while (parent != null)
{
queue.Push(parent);
parent = parent.Parent;
}
var generator = TreeView.ItemContainerGenerator;
while (queue.Count > 0)
{
var dequeue = queue.Pop();
TreeView.UpdateLayout();
var treeViewItem = (TreeViewItem)generator.ContainerFromItem(dequeue);
if (queue.Count > 0) treeViewItem.IsExpanded = true;
else treeViewItem.IsSelected = true;
generator = treeViewItem.ItemContainerGenerator;
}
}
Multiple tricks used in here:
a stack for expanding every item from top to bottom
ensure to use current level generator to find the item (really important)
the fact that generator for top-level items never return null
So far it works very well,
no need to pollute your types with new properties
no need to disable virtualization at all.
Although disabling virtualization from XAML works, I think it's better to disable it from the .cs file which uses ContainerFromItem
VirtualizingStackPanel.SetIsVirtualizing(listBox, false);
That way, you reduce the coupling between the XAML and the code; so you avoid the risk of someone breaking the code by touching the XAML.
Most probably this is a virtualization-related issue so ListBoxItem containers get generated only for currently visible items (see https://msdn.microsoft.com/en-us/library/system.windows.controls.virtualizingstackpanel(v=vs.110).aspx#Anchor_9)
If you are using ListBox I'd suggest switching to ListView instead - it inherits from ListBoxand it supports ScrollIntoView() method which you can utilize to control virtualization;
targetListView.ScrollIntoView(itemVM);
DoEvents();
ListViewItem itemContainer = targetListView.ItemContainerGenerator.ContainerFromItem(itemVM) as ListViewItem;
(the example above also utilizes the DoEvents() static method explained in more detail here; WPF how to wait for binding update to occur before processing more code?)
There are a few other minor differences between the ListBox and ListView controls (What is The difference between ListBox and ListView) - which should not essentially affect your use case.
VirtualizingStackPanel.IsVirtualizing="False" Makes the control fuzzy . See the below implementation. Which helps me to avoid the same issue.
Set your application VirtualizingStackPanel.IsVirtualizing="True" always.
See the link for detailed info
/// <summary>
/// Recursively search for an item in this subtree.
/// </summary>
/// <param name="container">
/// The parent ItemsControl. This can be a TreeView or a TreeViewItem.
/// </param>
/// <param name="item">
/// The item to search for.
/// </param>
/// <returns>
/// The TreeViewItem that contains the specified item.
/// </returns>
private TreeViewItem GetTreeViewItem(ItemsControl container, object item)
{
if (container != null)
{
if (container.DataContext == item)
{
return container as TreeViewItem;
}
// Expand the current container
if (container is TreeViewItem && !((TreeViewItem)container).IsExpanded)
{
container.SetValue(TreeViewItem.IsExpandedProperty, true);
}
// Try to generate the ItemsPresenter and the ItemsPanel.
// by calling ApplyTemplate. Note that in the
// virtualizing case even if the item is marked
// expanded we still need to do this step in order to
// regenerate the visuals because they may have been virtualized away.
container.ApplyTemplate();
ItemsPresenter itemsPresenter =
(ItemsPresenter)container.Template.FindName("ItemsHost", container);
if (itemsPresenter != null)
{
itemsPresenter.ApplyTemplate();
}
else
{
// The Tree template has not named the ItemsPresenter,
// so walk the descendents and find the child.
itemsPresenter = FindVisualChild<ItemsPresenter>(container);
if (itemsPresenter == null)
{
container.UpdateLayout();
itemsPresenter = FindVisualChild<ItemsPresenter>(container);
}
}
Panel itemsHostPanel = (Panel)VisualTreeHelper.GetChild(itemsPresenter, 0);
// Ensure that the generator for this panel has been created.
UIElementCollection children = itemsHostPanel.Children;
MyVirtualizingStackPanel virtualizingPanel =
itemsHostPanel as MyVirtualizingStackPanel;
for (int i = 0, count = container.Items.Count; i < count; i++)
{
TreeViewItem subContainer;
if (virtualizingPanel != null)
{
// Bring the item into view so
// that the container will be generated.
virtualizingPanel.BringIntoView(i);
subContainer =
(TreeViewItem)container.ItemContainerGenerator.
ContainerFromIndex(i);
}
else
{
subContainer =
(TreeViewItem)container.ItemContainerGenerator.
ContainerFromIndex(i);
// Bring the item into view to maintain the
// same behavior as with a virtualizing panel.
subContainer.BringIntoView();
}
if (subContainer != null)
{
// Search the next level for the object.
TreeViewItem resultContainer = GetTreeViewItem(subContainer, item);
if (resultContainer != null)
{
return resultContainer;
}
else
{
// The object is not under this TreeViewItem
// so collapse it.
subContainer.IsExpanded = false;
}
}
}
}
return null;
}
For anyone still having issues with this, I was able to work around this issue by ignoring the first selection changed event and using a thread to basically repeat the call. Here's what I ended up doing:
private int _hackyfix = 0;
private void OnMediaSelectionChanged(object sender, SelectionChangedEventArgs e)
{
//HACKYFIX:Hacky workaround for an api issue
//Microsoft's api for getting item controls for the flipview item fail on the very first media selection change for some reason. Basically we ignore the
//first media selection changed event but spawn a thread to redo the ignored selection changed, hopefully allowing time for whatever is going on
//with the api to get things sorted out so we can call the "ContainerFromItem" function and actually get the control we need I ignore the event twice just in case but I think you can get away with ignoring only the first one.
if (_hackyfix == 0 || _hackyfix == 1)
{
_hackyfix++;
Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
{
OnMediaSelectionChanged(sender, e);
});
}
//END OF HACKY FIX//Actual code you need to run goes here}
EDIT 10/29/2014: You actually don't even need the thread dispatcher code. You can set whatever you need to null to trigger the first selection changed event and then return out of the event so that future events work as expected.
private int _hackyfix = 0;
private void OnMediaSelectionChanged(object sender, SelectionChangedEventArgs e)
{
//HACKYFIX: Daniel note: Very hacky workaround for an api issue
//Microsoft's api for getting item controls for the flipview item fail on the very first media selection change for some reason. Basically we ignore the
//first media selection changed event but spawn a thread to redo the ignored selection changed, hopefully allowing time for whatever is going on
//with the api to get things sorted out so we can call the "ContainerFromItem" function and actually get the control we need
if (_hackyfix == 0)
{
_hackyfix++;
/*
Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
{
OnMediaSelectionChanged(sender, e);
});*/
return;
}
//END OF HACKY FIX
//Your selection_changed code here
}

How do I get the Children of a ContentPresenter?

Using the code I can get a content presenter. I would like to locate the first textbox inside it and set the focus accordingly.
Dim obj = TerritoryListViewer.ItemContainerGenerator.ContainerFromItem(myModel)
You can use VisualTreeHelper static class to crawl controls tree.
This is how it can be accomplished in c# (sorry I'm VB dyslexic))
T FindFirstChild<T>(FrameworkElement element) where T: FrameworkElement
{
int childrenCount = VisualTreeHelper.GetChildrenCount(element);
var children = new FrameworkElement[childrenCount];
for (int i = 0; i < childrenCount; i++)
{
var child = VisualTreeHelper.GetChild(element, i) as FrameworkElement;
children[i] = child;
if (child is T)
return (T)child;
}
for (int i = 0; i < childrenCount; i++)
if (children[i] != null)
{
var subChild = FindFirstChild<T>(children[i]);
if (subChild != null)
return subChild;
}
return null;
}
ContentPresenter has the only child. You get the child simply by
VisualTreeHelper.GetChild(yourContentPresenterObj, 0);
If you need to go deeper - down to a first found TextBox, then, yes, you use the more comprehensive approach suggested by #alpha-mouse.
Dim myContentPresenter = CType(obj, ContentPresenter)
Dim myDataTemplate = myContentPresenter.ContentTemplate
Dim target = CType(myDataTemplate.FindName("txtQuantity", myContentPresenter), TextBox)
In my case I needed to iterate on all controls of a certain base type placed on a custom canvas which was being used inside an ItemsControl.
This Linq expression was used to get those controls from within MeasureOverride():
var foobarControls =
InternalChildren
.OfType<ContentPresenter>()
.Where(c => VisualTreeHelper.GetChildrenCount(c) > 0)
.Select(c => VisualTreeHelper.GetChild(c, 0))
.OfType<FoobarControlBase>();
This guards against cases where the ContentPresenter had no children. I found in some instances depending on when this was called the visual tree might not be established and as a result the ContentPresenters would have no children. (This situation might have been a bug in itself, actually, but nonetheless this code turned out to be reliable.)

What does the PathGeneratedInternally flag do in a WPF binding?

I've just answered a question over here where I said that there is no functional difference between
{Binding TargetProperty}
and
{Binding Path=TargetProperty}
and, as far as I'm aware what I have written is fundamentally correct. However the idea that one will use the constructor and the other sets the property got me thinking that there could be a difference, so I whipped open reflector and had a look.
The constructor has the following code in it:
public Binding(string path)
{
this._source = UnsetSource;
if (path != null)
{
if (Dispatcher.CurrentDispatcher == null)
{
throw new InvalidOperationException();
}
this._ppath = new PropertyPath(path, new object[0]);
this._attachedPropertiesInPath = -1;
}
}
The path property is this:
public PropertyPath Path
{
get
{
return this._ppath;
}
set
{
base.CheckSealed();
this._ppath = value;
this._attachedPropertiesInPath = -1;
base.ClearFlag(BindingBase.BindingFlags.PathGeneratedInternally);
}
}
So when you set the path through the property the PathGeneratedInternally flag is cleared. Now, this flag isn't exposed anywhere publicly directly, but it does seem to be used in a few places:
internal void UsePath(PropertyPath path)
{
this._ppath = path;
base.SetFlag(BindingBase.BindingFlags.PathGeneratedInternally);
}
[EditorBrowsable(EditorBrowsableState.Never)]
public bool ShouldSerializePath()
{
return ((this._ppath != null) && !base.TestFlag(BindingBase.BindingFlags.PathGeneratedInternally));
}
I'm sure it's all fairly inconsequential, but does anyone out there know what this flag means and why it maybe different depending on how you declare the binding?
The key is to see where the UsePath method is referenced from. By default the flag won't be set, so clearing it is basically a no-op. There is no reason to clear it in the constructor, because you know it hasn't been set in that case (because the object is still being constructed).
The UsePath method is only called in one location and that's the ClrBindingWorker constructor. If you look in there you will see they automatically create a "blank" or "empty" path and pass that to UsePath.
I suspect they do this so the Path is "valid" when used internally, even if it just refers to the binding source (which is the default behavior when no path is given). If you later set the Path property on the Binding, the flag that indicates the Path was automatically generated must be cleared.

AssociatedObject.FindName in Silverlight behavior OnAttached method returns null

I'm making a Silverlight behavior to enable dragging an element by a contained "drag handle" element (rather than the whole element being draggable). Think of it like a window title bar.
In the OnAttached method I am calling: AssociatedObject.FindName(DragHandle)
but this is returning null.
I then tried handling the AssociatedObject's Loaded event and running my code there, but I still get a null returned.
Am I misunderstanding what FindName is able to do? The AssociatedObject is in an ItemsControl (I want a collection of draggable elements). So is there some kind of namescope problem?
Yes, it sounds like a namescope problem. The MSDN documentation on XAML namescopes goes over how namesopes are defined for templates and item controls. Are you using a template for the items in your ItemsControl?
You may just have to walk the visual tree recursively with something like this to find the correct element by name:
private static FrameworkElement FindChildByName(FrameworkElement parent, string name)
{
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(parent); i++)
{
FrameworkElement child = VisualTreeHelper.GetChild(parent, i) as FrameworkElement;
if (child != null && child.Name == name)
{
return child;
}
else
{
FrameworkElement grandChild = FindChildByName(child, name);
if (grandChild != null)
{
return grandChild;
}
}
}
return null;
}

Resources