How to bring into view all TreeViewItems of expanded TreeViewItem - wpf

On my Window I have TreeView. TreeView.ItemsSource is binded to my data (hierarchical data structure). When I expand some TreeViewItem that is on the bottom of the current scrollbar position, my subitems are hidden and I have to scroll to see them. Is there any way to bring all subitems of expanded item into view?
I have tried this, but didn't work:
public void TreeViewItem_Expanded(object sender, RoutedEventArgs e)
{
TreeViewItem tvi = e.OriginalSource as TreeViewItem;
if (tvi != null)
{
Debug.WriteLine("TreeNode '{0}' was expanded", tvi.Header);
tvi.BringIntoView();
}
}

Basically, select the last sub-item and bring it into view when an item is expanded. If it has no subitems, bring the item itself into view.
The tricky part is, subitems are not necessarily available when the event is executed, so I propose you check the ItemContainerGenerator.Status and if it's not yet done, subscribe to the ItemContainerGenerator.StatusChanged event.
The following code is only tested with static items, if it's making problem for dynamic data sources, I may have to re-check a few details.
void TreeViewItem_Expanded(object sender, RoutedEventArgs e)
{
TreeViewItem tvi = e.OriginalSource as TreeViewItem;
if (tvi != null)
{
if (tvi.HasItems)
{
if (tvi.ItemContainerGenerator.Status == GeneratorStatus.ContainersGenerated)
{
BringLastItemIntoView(tvi.ItemContainerGenerator);
}
else
{
tvi.ItemContainerGenerator.StatusChanged += ItemContainerGenerator_StatusChanged;
}
}
else
{
tvi.BringIntoView();
}
}
}
void ItemContainerGenerator_StatusChanged(object sender, EventArgs e)
{
var s = sender as ItemContainerGenerator;
if (s.Status == GeneratorStatus.ContainersGenerated)
{
BringLastItemIntoView(s);
s.StatusChanged -= ItemContainerGenerator_StatusChanged;
}
}
void BringLastItemIntoView(ItemContainerGenerator generator)
{
var tvi = generator.ContainerFromItem(generator.Items.LastOrDefault()) as TreeViewItem;
if (tvi != null)
{
tvi.BringIntoView();
}
}

Related

Content of TabItem stays visibile when set to Collapsed/Hidden

I have a TabControl that displays default information for objects that can be selected by the user in a list.
Unfortunately not all of the TabItems apply to all types of objects. That's why I decided to use DataTriggers to hide some of them in such cases. When testing however I noticed that when the a TabItem is already selected while being set to collapsed then only the header vanishes, but the content of the TabItems stays visible.
When searching for a solution I only found this very old thread here:
WPF - TabItem Contents still visible when tabitem.visibility=hidden
I was wondering if there was is nicer solution today. The only thing that I could think of would be a custom TabControl that would look somehow like this:
public class MyTabControl : System.Windows.Controls.TabControl
{
public MyTabControl() : base()
{
var view = CollectionViewSource.GetDefaultView(this.Items);
view.CollectionChanged += TabControl_CollectionChanged;
}
private void TabControl_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
{
if (e.NewItems != null)
{
foreach (TabItem tabItem in e.NewItems)
{
tabItem.IsVisibleChanged += TabItem_IsVisibleChanged;
}
}
else if (this.Items != null)
{
foreach (TabItem tabItem in this.Items)
{
tabItem.IsVisibleChanged += TabItem_IsVisibleChanged;
}
}
}
private void TabItem_IsVisibleChanged(object sender, DependencyPropertyChangedEventArgs e)
{
TabItem tabItem = sender as TabItem;
if (tabItem != null && tabItem.IsSelected && tabItem.Visibility != Visibility.Visible)
{
this.SelectedIndex = 0;
}
}
}
However this means that I have to use my own TabControl over the default one. Can anyone think of an even nicer solution?

Drag and drop multiple instances of user controls in WPF

The given code works fine with dragging and dropping one instance of control. If I try to drop the same instance again it throws an exception:
Specified element is already the logical child of another element. Disconnect it first.
How do I drop multiple instances of user controls on my Canvas, similar to how Visual Studio toolbox does?
public MainWindow()
{
InitializeComponent();
LoadUsercontrols();
}
private void LoadUsercontrols()
{
List<string> userControlKeys = new List<string>();
userControlKeys.Add("testCtrl1");
userControlKeys.Add("testCtrl2");
Type type = this.GetType();
Assembly assembly = type.Assembly;
foreach (string userControlKey in userControlKeys)
{
userControlFullName = String.Format("{0}.TestControls.{1}", type.Namespace, userControlKey);
UserControl userControl = new UserControl();
userControl = (UserControl)assembly.CreateInstance(userControlFullName);
_userControls.Add(userControlKey, userControl);
}
}
private void TreeViewItem_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
startPoint = e.GetPosition(null);
}
private void TreeViewItem_PreviewMouseMove(object sender, MouseEventArgs e)
{
// Get the current mouse position
System.Windows.Point mousePos = e.GetPosition(null);
Vector diff = startPoint - mousePos;
if (e.LeftButton == MouseButtonState.Pressed &&
Math.Abs(diff.X) > SystemParameters.MinimumHorizontalDragDistance &&
Math.Abs(diff.Y) > SystemParameters.MinimumVerticalDragDistance)
{
TreeView treeView = sender as TreeView;
TreeViewItem treeViewItem = FindAnchestor<TreeViewItem>((DependencyObject)e.OriginalSource);
if (treeViewItem != null)
{
Type type = this.GetType();
Assembly assembly = type.Assembly;
DataObject dragData = new DataObject("myFormat", _userControls[((System.Windows.Controls.HeaderedItemsControl)(treeViewItem)).Header.ToString()]);
DragDrop.DoDragDrop(treeViewItem, dragData, DragDropEffects.Copy);
}
}
}
private static T FindAnchestor<T>(DependencyObject current) where T : DependencyObject
{
do
{
if (current is T)
{
return (T)current;
}
current = VisualTreeHelper.GetParent(current);
}
while (current != null);
return null;
}
private void MyDesignerCanvas_DragEnter(object sender, DragEventArgs e)
{
if (!e.Data.GetDataPresent("myFormat") || sender == e.Source)
{
e.Effects = DragDropEffects.None;
}
}
private void MyDesignerCanvas_Drop(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent("myFormat"))
{
if (treeItem != null)
{
UserControl myCanvasItem = e.Data.GetData("myFormat") as UserControl;
UserControl newCanvastItem = new UserControl
{
Content = _userControls[((System.Windows.Controls.HeaderedItemsControl)(treeItem)).Header.ToString()]
};
Point position = e.GetPosition(MyDesignerCanvas);
DesignerCanvas.SetLeft(newCanvastItem, position.X);
DesignerCanvas.SetTop(newCanvastItem, position.Y);
DesignerCanvas.SetZIndex(newCanvastItem, 1);
MyDesignerCanvas.Children.Add(newCanvastItem);
}
}
}
In XAML Code:
<TreeView x:Name="presetTreeView4" Grid.Row="1" >
<TreeViewItem Header="testCtrl1" Selected="TreeViewItem_Selected" PreviewMouseLeftButtonDown="TreeViewItem_PreviewMouseLeftButtonDown" PreviewMouseMove="TreeViewItem_PreviewMouseMove"/>
<TreeViewItem Header="testCtrl2" Selected="TreeViewItem_Selected" PreviewMouseLeftButtonDown="TreeViewItem_PreviewMouseLeftButtonDown" PreviewMouseMove="TreeViewItem_PreviewMouseMove"/>
</TreeView>
<s:DesignerCanvas x:Name="MyDesignerCanvas" AllowDrop="True" Drop="MyDesignerCanvas_Drop" DragEnter="MyDesignerCanvas_DragEnter" Background="#A6B0D2F5" DockPanel.Dock="Bottom" Margin="0" >
</s:DesignerCanvas>
You cannot add the same control to different containers - a control can only appear once in the visual tree.
Instead of loading the user controls in advance, you should construct them at MyDesignerCanvas_Drop (i.e. use Activator the same way you're using it right now in LoadUsercontrols) and assign the resulting control to the UserControl.Content.
I think you have to clone control _userControls[((System.Windows.Controls.HeaderedItemsControl)(treeItem)).Header.ToString()] in MyDesignerCanvas_Drop

WPF MVVM design question

In my View I have a TreeView with a event "TreeView_MouseLeftButtonDown". If it fires it proofs if the mouse clicked on a TreeViewItem. If not it deselects the last TreeViewItem.
My question is, should i do this in the code-behind or call a static methode in the viewmodel-class? How would you solve this?
The Methode:
private void treeView_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
if (sender != null)
{
var treeView = sender as TreeView;
if (treeView != null && treeView.SelectedItem != null)
TreeViewHelper.ReturnTreeViewItem(ref treeView, (XmlNode)treeView.SelectedItem).IsSelected = false;
}
}
XAML:
<TreeView ... KeyDown="TreeView_KeyDown"
MouseLeftButtonDown="TreeView_MouseLeftButtonDown"
SelectedItemChanged="TreeView_SelectedItemChanged" />
You are trying to add a behaviour to the TreeView.
The way I would implement this would be using Attached Properties. I would create an attached property called VerifiesLeftClick or similar and implement the logic in there. This way you do not need an event in the code behind.
See here for samples.
I made for you solution using attached behaviors which were pretty well described here Introduction to Attached Behaviors in WPF by Josh Smith
My solution:
public static class TreeViewBehavior
{
public static bool GetIsResetMouseLeftButtonDown(TreeView treeView)
{
return (bool)treeView.GetValue(IsResetMouseLeftButtonDownProperty);
}
public static void SetIsResetMouseLeftButtonDown(TreeView treeViewItem, bool value)
{
treeViewItem.SetValue(IsResetMouseLeftButtonDownProperty, value);
}
public static readonly DependencyProperty IsResetMouseLeftButtonDownProperty =
DependencyProperty.RegisterAttached("PreviewMouseLeftButtonDown", typeof(bool), typeof(TreeViewBehavior),
new UIPropertyMetadata(false, OnIsMouseLeftButtonDownChanged));
static void OnIsMouseLeftButtonDownChanged(DependencyObject depObj, DependencyPropertyChangedEventArgs e)
{
TreeView item = depObj as TreeView;
if (item == null)
return;
if (e.NewValue is bool == false)
return;
if ((bool)e.NewValue)
{
item.PreviewMouseLeftButtonDown += OnMouseLeftButtonDown;
}
else
{
item.MouseLeftButtonDown -= OnMouseLeftButtonDown;
}
}
static void OnMouseLeftButtonDown(object sender, RoutedEventArgs e)
{
var tempItem = e.Source as TreeViewItem;
if (tempItem != null && tempItem.IsSelected == false)
{
tempItem.IsSelected = true;
}
else
{
var tree = e.Source as TreeView;
if (tree != null && tree.SelectedItem != null)
{
var selItem = (tree.SelectedItem as TreeViewItem);
if (selItem != null)
{
selItem.IsSelected = false;
}
}
}
}
}
and then in View you should add this:
<TreeView local:TreeViewBehavior.IsResetMouseLeftButtonDown="True">
I hope my solution do what you are trying to achieve.

WPF TreeView, get TreeViewItem in PreviewMouseDown event

How can I determine TreeViewItem clicked in PreviewMouseDown event?
The following seems to work:
private void myTreeView_PreviewMouseDown(object sender, MouseButtonEventArgs e)
{
TreeViewItem item = GetTreeViewItemClicked((FrameworkElement)e.OriginalSource,
myTreeView);
...
}
private TreeViewItem GetTreeViewItemClicked(FrameworkElement sender, TreeView treeView)
{
Point p = ((sender as FrameworkElement)).TranslatePoint(new Point(0, 0), treeView);
DependencyObject obj = treeView.InputHitTest(p) as DependencyObject;
while (obj != null && !(obj is TreeViewItem))
obj = VisualTreeHelper.GetParent(obj);
return obj as TreeViewItem;
}
I originally used an extension method on TreeView that takes a UIElement--the sender of the PreviewMouseDown event--like this:
private void MyTreeView_PreviewMouseDown(object sender, MouseButtonEventArgs e)
{
var uiElement = sender as UIElement;
var treeViewItem = myTreeView.TreeViewItemFromChild(uiElement);
}
Here's the extension method (it checks the child itself in case you clicked right on a TreeViewItem directly)...
public static TreeViewItem TreeViewItemFromChild(this TreeView treeView, UIElement child)
{
UIElement proposedElement = child;
while ((proposedElement != null) && !(proposedElement is TreeViewItem))
proposedElement = VisualTreeHelper.GetParent(proposedElement) as UIElement;
return proposedElement as TreeViewItem;
}
Update:
However, I've since switched it to a more generic version that I can use anywhere.
public static TAncestor FindAncestor<TAncestor>(this UIElement uiElement)
{
while ((uiElement != null) && !(uiElement is TAncestor))
retVal = VisualTreeHelper.GetParent(uiElement) as UIElement;
return uiElement as TAncestor;
}
That either finds the type you're looking for (again, including checking itself) or returns null
You'd use it in the same PreviewMouseDown handler like so...
private void MyTreeView_PreviewMouseDown(object sender, MouseButtonEventArgs e)
{
var uiElement = sender as UIElement;
var treeViewItem = uiElement.FindAncestor<TreeViewItem>();
}
This came in very handy for when my TreeViewItem had a CheckBox in its template and I wanted to select the item when the user clicked the checkbox which normally swallows the event.
Hope this helps!

How to deselect all selected items in a WPF treeview when clicking on some empty area?

I've got a rather funny problem with WPF. I have a tree-view, and selecting items works fine so far. The problem is, I want to unselect the currently selected item when the user clicks inside the blank area of the treeview. By default, the treeview keeps the current item selected, and I have added a context-menu option to deselect it, which is rather hardcore:
// Note: This is done recursivly from the start, so it
// works for child items as well
treeView.ItemContainerGenerator.ContainerFromItem(treeView.SelectedItem) as TreeViewItem).IsSelected = false;
Moreover, this is counter-intuitive, as it requires the user to right-click first, and second, after deselecting it with this way, the user cannot select it any more by clicking on the item. How is this supposed to work?
Edit: Some more information: I've added a handler to the TreeView to handle mouse click events, but the sender is always a TreeView instance, even if I click directly on a TreeViewItem. If I add a handler to my TreeView.ItemTemplate instead (i.e. the first child in the template), I never get events when I click on the empty area (which is rather logical). The code looks like this:
private void MyTreeView_MouseUp(object sender, System.Windows.Input.MouseButtonEventArgs e)
{
if ((sender as TreeViewItem) == null)
{
// Always triggered
System.Diagnostics.Trace.Write("Empty area clicked");
}
}
And the XAML for this is:
<TreeView x:Name="MyTreeView" Margin="3" MouseUp="MyTreeView_MouseUp">
I found this to work much better for me. I check the originalsource which for me if it comes form a treeviewitem will be an image or a textblock. I also use a view object with a HierarchicalDataTemplate and the BasicTreeViewBase is the base class for all of my different objects. Here is the code.
private void TemplateTreeView_MouseDown(object sender, MouseButtonEventArgs e)
{
if (e.ChangedButton == MouseButton.Right && !(e.OriginalSource is Image) && !(e.OriginalSource is TextBlock))
{
BasicTreeViewBase item = TemplateTreeView.SelectedItem as BasicTreeViewBase;
if (item != null)
{
TemplateTreeView.Focus();
item.IsSelected = false;
}
}
}
The un-selectable problem can be solved with a call to Focus on the TreeView after setting TreeViewItem.IsSelected.
There can be two more problem :
The treeview is binded so the SelectedItem is an item of the binded collection.
There is many levels so ItemContainerGenerator do not contain deepest level objects
for all this reason i use this function, but the selection must not fire any events.
private void UnselectTreeViewItem(TreeView pTreeView)
{
if(pTreeView.SelectedItem == null)
return;
if(pTreeView.SelectedItem is TreeViewItem)
{
(pTreeView.SelectedItem as TreeViewItem).IsSelected = false;
}
else
{
TreeViewItem item = pTreeView.ItemContainerGenerator.ContainerFromIndex(0) as TreeViewItem;
if (item != null)
{
item.IsSelected = true;
item.IsSelected = false;
}
}
}
I implemented a general selection control once, and required this behaviour.
This is how my method looked (adapted for treeview):
protected override void OnMouseUp(MouseButtonEventArgs e)
{
base.OnMouseUp(e);
DependencyObject dpSource = e.OriginalSource as DependencyObject;
if (dpSource.FindVisualAncestor(o => typeof(TreeViewItem).IsAssignableFrom(o.GetType())) == null)
UnselectAll();
}
Basically, walk up the tree from the source. If a TreeViewItem was not found, than the user clicked empty space.
Use the extension class below
public static class TreeViewExtensions
{
public static TreeViewItem ContainerFromItem(this TreeView treeView, object item)
{
TreeViewItem containerThatMightContainItem = (TreeViewItem)treeView.ItemContainerGenerator.ContainerFromItem(item);
if (containerThatMightContainItem != null)
return containerThatMightContainItem;
else
return ContainerFromItem(treeView.ItemContainerGenerator, treeView.Items, item);
}
private static TreeViewItem ContainerFromItem(ItemContainerGenerator parentItemContainerGenerator, ItemCollection itemCollection, object item)
{
foreach (object curChildItem in itemCollection)
{
TreeViewItem parentContainer = (TreeViewItem)parentItemContainerGenerator.ContainerFromItem(curChildItem);
TreeViewItem containerThatMightContainItem = (TreeViewItem)parentContainer.ItemContainerGenerator.ContainerFromItem(item);
if (containerThatMightContainItem != null)
return containerThatMightContainItem;
TreeViewItem recursionResult = ContainerFromItem(parentContainer.ItemContainerGenerator, parentContainer.Items, item);
if (recursionResult != null)
return recursionResult;
}
return null;
}
}
Then in MouseDown event of treeview use the extension method as below:
private void trview_MouseDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
{
if ((sender as TreeViewItem) == null)
{
if (this.trview.ContainerFromItem(trview.SelectedItem) != null)
{
this.trview.ContainerFromItem(trview.SelectedItem).IsSelected = false;
}
}
this.trview.Focus();
}
Hope it works for you. I have it working in this way...
I was running into this situation myself with a custom Tree List View implementation after looking for a long time I finally found a solution that worked for me.
The full explanation can be found at http://social.msdn.microsoft.com/Forums/vstudio/en-US/36aca7f7-0b47-488b-8e16-840b86addfa3/getting-treeviewitem-for-the-selected-item-in-a-treeview
The basic idea is you capture the TreeViewItem.Selected event and save the source of the event into the Tag attribute on your TreeView. Then when you need to clear it, you can access the Tag attribute on your control and set the IsSelected value to False. This works for me with 2 levels of nested children. Hopefully it will work for you.
For persistence sake:
TreeView declaration
<TreeView Name="myTreeView" TreeViewItem.Selected="OnItemSelected"
ItemsSource="{Binding Source={StaticResource myHierarchicalData}}"/>
Event Handler
private void OnItemSelected(object sender, RoutedEventArgs e)
{
myTreeView.Tag = e.OriginalSource;
}
Clear selection logic
if (myTreeView.SelectedItem != null)
{
TreeViewItem selectedTVI = myTreeView.Tag as TreeViewItem;
// add your code here mine was selectedTVI.IsSelected = false;
}
This will deselect the currently selected TreeViewItem if none were clicked:
private void MyTreeView_PreviewMouseDown(object sender, MouseButtonEventArgs e) {
if ((sender as TreeViewItem) == null) {
TreeViewItem item = MyTreeView.SelectedItem as TreeViewItem;
if(item != null){
item.IsSelected = false;
}
}
}
Hope this is what you were looking for!
MVVM: Call this method in the eventhandler righ/left mouse click:
private void SetTreeViewSelection(object sender, MouseButtonEventArgs mouseButtonEventArgs)
{
var treeView = (TreeView)sender;
if (treeView.SelectedItem == null)
{
return;
}
IInputElement dropNode = treeView.InputHitTest(mouseButtonEventArgs.GetPosition(treeView));
if (dropNode is ScrollViewer)
{
var myBindableObject = (MyBindableObject)treeView.SelectedItem;
myBindableObject.IsSelected = false;
}
}
For a C# treeview you use treeview.SelectedNode = null; I'm not sure if this works for WPF.

Resources