如何以编程方式选择WPF TreeView
中的项目? ItemsControl
模型似乎阻止了它。
答案 0 :(得分:38)
对于仍在寻找正确解决此问题的人,请参见下文。我在DaWanderer的代码项目文章“WPF TreeView Selection”http://www.codeproject.com/KB/WPF/TreeView_SelectionWPF.aspx的评论中找到了这个。 它由Kenrae于2008年11月25日发布。这对我来说非常有用。谢谢Kenrae!
让自己的数据对象拥有IsSelected属性(我也建议使用IsExpanded属性),而不是遍历树。使用TreeView上的ItemContainerStyle属性为TreeViewItems定义样式,该属性将TreeViewItem中的这些属性绑定到数据对象。像这样:
<Style x:Key="LibraryTreeViewItemStyle"
TargetType="{x:Type TreeViewItem}">
<Setter Property="IsExpanded"
Value="{Binding IsExpanded, Mode=TwoWay}" />
<Setter Property="IsSelected"
Value="{Binding IsSelected, Mode=TwoWay}" />
<Setter Property="FontWeight"
Value="Normal" />
<Style.Triggers>
<Trigger Property="IsSelected"
Value="True">
<Setter Property="FontWeight"
Value="Bold" />
</Trigger>
</Style.Triggers>
</Style>
<TreeView ItemsSource="{Binding Path=YourCollection}"
ItemContainerStyle="{StaticResource LibraryTreeViewItemStyle}"
ItemTemplate={StaticResource YourHierarchicalDataTemplate}/>
答案 1 :(得分:22)
由于一些奇怪的原因,这是一个真正的痛苦,您必须使用ContainerFromItem来获取容器,然后调用select方法。
// selectedItemObject is not a TreeViewItem, but an item from the collection that
// populated the TreeView.
var tvi = treeView.ItemContainerGenerator.ContainerFromItem(selectedItemObject)
as TreeViewItem;
if (tvi != null)
{
tvi.IsSelected = true;
}
曾经有关于如何做到这一点的博客文章here,但现在链接已经死了。
答案 2 :(得分:22)
您需要获取TreeViewItem
,然后将IsSelected
设置为true
。
答案 3 :(得分:7)
我已成功使用此代码:
public static TreeViewItem FindTviFromObjectRecursive(ItemsControl ic, object o) {
//Search for the object model in first level children (recursively)
TreeViewItem tvi = ic.ItemContainerGenerator.ContainerFromItem(o) as TreeViewItem;
if (tvi != null) return tvi;
//Loop through user object models
foreach (object i in ic.Items) {
//Get the TreeViewItem associated with the iterated object model
TreeViewItem tvi2 = ic.ItemContainerGenerator.ContainerFromItem(i) as TreeViewItem;
tvi = FindTviFromObjectRecursive(tvi2, o);
if (tvi != null) return tvi;
}
return null;
}
用法:
var tvi = FindTviFromObjectRecursive(TheTreeView, TheModel);
if (tvi != null) tvi.IsSelected = true;
答案 4 :(得分:5)
这并不像看起来那么简单,Steven提供的链接在2008年发布了一个解决方案,该解决方案可能仍然有效,但不会处理Virtualized TreeViews。此外,该条的评论中还提到了许多其他问题。没有违法行为,但我也遇到了同样的问题,无法找到完美的解决方案。以下是一些帮助我很多的文章/帖子的链接 -
如何在TreeView中展开项目? - 第三部分: http://bea.stollnitz.com/blog/?p=59
以编程方式选择TreeView中的项目: http://blog.quantumbitdesigns.com/2008/07/22/programmatically-selecting-an-item-in-a-treeview/#respond
TreeView,TreeViewItem和IsSelected: http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/7e368b93-f509-4cd6-88e7-561e8d3246ae/
答案 5 :(得分:2)
我写了一个扩展方法:
using System.Windows.Controls;
namespace Extensions
{
public static class TreeViewEx
{
/// <summary>
/// Select specified item in a TreeView
/// </summary>
public static void SelectItem(this TreeView treeView, object item)
{
var tvItem = treeView.ItemContainerGenerator.ContainerFromItem(item) as TreeViewItem;
if (tvItem != null)
{
tvItem.IsSelected = true;
}
}
}
}
我可以这样使用:
if (_items.Count > 0)
_treeView.SelectItem(_items[0]);
答案 6 :(得分:1)
如果你想选择位于孩子的孩子中的项目,你可以使用递归来做到这一点。
public bool Select(TreeViewItem item, object select) // recursive function to set item selection in treeview
{
if (item == null)
return false;
TreeViewItem child = item.ItemContainerGenerator.ContainerFromItem(select) as TreeViewItem;
if (child != null)
{
child.IsSelected = true;
return true;
}
foreach (object c in item.Items)
{
bool result = Select(item.ItemContainerGenerator.ContainerFromItem(c) as TreeViewItem, select);
if (result == true)
return true;
}
return false;
}
答案 7 :(得分:0)
试试这个
/// <summary>
/// Selects the tree view item.
/// </summary>
/// <param name="Collection">The collection.</param>
/// <param name="Value">The value.</param>
/// <returns></returns>
private TreeViewItem SelectTreeViewItem(ItemCollection Collection, String Value)
{
if (Collection == null) return null;
foreach(TreeViewItem Item in Collection)
{
/// Find in current
if (Item.Header.Equals(Value))
{
Item.IsSelected = true;
return Item;
}
/// Find in Childs
if (Item.Items != null)
{
TreeViewItem childItem = this.SelectTreeViewItem(Item.Items, Value);
if (childItem != null)
{
Item.IsExpanded = true;
return childItem;
}
}
}
return null;
}
参考:http://amastaneh.blogspot.com/2011/06/wpf-selectedvalue-for-treeview.html
答案 8 :(得分:0)
我只想到我会使用我所使用的解决方案,以防这可以帮助任何人。请注意,执行此操作的最佳方法是根据kuninl的答案使用“IsSelected”等绑定属性,但在我的情况下,它是一个不遵循MVVM的遗留应用程序,因此我最终得到了以下内容。
private void ChangeSessionSelection()
{
foreach (SessionContainer item in this.treeActiveSessions.Items)
{
var treeviewItem = this.treeActiveSessions.ItemContainerGenerator.ContainerFromItem(item) as TreeViewItem;
if (item.Session == this.selectedSession.Session)
{
treeviewItem.IsSelected = true;
treeviewItem.IsExpanded = true;
}
else
{
treeviewItem.IsSelected = false;
treeviewItem.IsExpanded = false;
}
}
}
这样做是选择并展开UI中的树视图项,该项代表后面代码中的选定数据项。这样做的目的是在同一窗口中的项目控件中更改用户选择时,在树视图中进行选择更改。
答案 9 :(得分:0)
我创建了一个方法VisualTreeExt.GetDescendants<T>
,它返回一个与指定类型匹配的可枚举元素集合:
public static class VisualTreeExt
{
public static IEnumerable<T> GetDescendants<T>(DependencyObject parent) where T : DependencyObject
{
var count = VisualTreeHelper.GetChildrenCount(parent);
for (var i = 0; i < count; ++i)
{
// Obtain the child
var child = VisualTreeHelper.GetChild(parent, i);
if (child is T)
yield return (T)child;
// Return all the descendant children
foreach (var subItem in GetDescendants<T>(child))
yield return subItem;
}
}
}
当您要求VisualTreeHelperExt.GetDescendants<TreeViewItem>(MyAmazingTreeView)
时,您将获得所有TreeViewItem
个孩子。您可以使用以下代码选择特定值:
var treeViewItem = VisualTreeExt.GetDescendants<TreeViewItem>(MyTreeView).FirstOrDefault(tvi => tvi.DataContext == newValue);
if (treeViewItem != null)
treeViewItem.IsSelected = true;
这是一个肮脏的解决方案(并且可能不是最有效的)并且如果您使用虚拟化TreeView将无法工作,因为它取决于实际视觉元素的存在。但它适用于我的情况......
答案 10 :(得分:0)
是的..我知道问题被问到很多年过去了但是......仍然没有快速解决这个问题..所以:
以下将执行OP要求的内容。
我基本上做的是阅读本页面中的所有答案,并按照所有相关链接为这个恼人的问题创建一个一劳永逸解决方案。
好处:
此部分是您需要复制的唯一代码,其他部分仅用于帮助完成示例。
public static class TreeViewSelectedItemExBehavior
{
private static List<TreeView> isRegisteredToSelectionChanged = new List<TreeView>();
public static readonly DependencyProperty SelectedItemExProperty =
DependencyProperty.RegisterAttached("SelectedItemEx",
typeof(object),
typeof(TreeViewSelectedItemExBehavior),
new FrameworkPropertyMetadata(new object(), FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, OnSelectedItemExChanged, null));
#region SelectedItemEx
public static object GetSelectedItemEx(TreeView target)
{
return target.GetValue(SelectedItemExProperty);
}
public static void SetSelectedItemEx(TreeView target, object value)
{
target.SetValue(SelectedItemExProperty, value);
var treeViewItemToSelect = GetTreeViewItem(target, value);
if (treeViewItemToSelect == null)
{
if (target.SelectedItem == null)
return;
var treeViewItemToUnSelect = GetTreeViewItem(target, target.SelectedItem);
treeViewItemToUnSelect.IsSelected = false;
}
else
treeViewItemToSelect.IsSelected = true;
}
public static void OnSelectedItemExChanged(DependencyObject depObj, DependencyPropertyChangedEventArgs e)
{
var treeView = depObj as TreeView;
if (treeView == null)
return;
if (!isRegisteredToSelectionChanged.Contains(treeView))
{
treeView.SelectedItemChanged += TreeView_SelectedItemChanged;
isRegisteredToSelectionChanged.Add(treeView);
}
}
#endregion
private static void TreeView_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
{
var treeView = (TreeView)sender;
SetSelectedItemEx(treeView, e.NewValue);
}
#region Helper Structures & Methods
public class MyVirtualizingStackPanel : VirtualizingStackPanel
{
/// <summary>
/// Publically expose BringIndexIntoView.
/// </summary>
public void BringIntoView(int index)
{
BringIndexIntoView(index);
}
}
/// <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 static 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;
}
/// <summary>Search for an element of a certain type in the visual tree.</summary>
/// <typeparam name="T">The type of element to find.</typeparam>
/// <param name="visual">The parent element.</param>
/// <returns></returns>
private static T FindVisualChild<T>(Visual visual) where T : Visual
{
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(visual); i++)
{
Visual child = (Visual)VisualTreeHelper.GetChild(visual, i);
if (child != null)
{
T correctlyTyped = child as T;
if (correctlyTyped != null)
{
return correctlyTyped;
}
T descendent = FindVisualChild<T>(child);
if (descendent != null)
{
return descendent;
}
}
}
return null;
}
#endregion
}
这是一个关于TreeView线在XAML中的样子的例子:
<TreeView x:Name="trvwSs"
Grid.Column="2" Grid.Row="1" Margin="4" ItemsSource="{Binding ItemsTreeViewSs}"
behaviors:TreeViewSelectedItemExBehavior.SelectedItemEx="{Binding SelectedItemTreeViewSs}" />
唯一需要担心的是确保您要绑定到SelectedItemEx的视图模型属性不为null。但这不是一个特例。只是提到它以防人们感到困惑。
public class VmMainContainer : INotifyPropertyChanged
{
private object selectedItemTreeViewSs = new object();
private ObservableCollection<object> selectedItemsTreeViewSs = new ObservableCollection<object>();
private ObservableCollection<VmItem> itemsTreeViewSs = new ObservableCollection<VmItem>();
public object SelectedItemTreeViewSs
{
get
{
return selectedItemTreeViewSs;
}
set
{
selectedItemTreeViewSs = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(SelectedItemTreeViewSs)));
}
}
public ObservableCollection<object> SelectedItemsTreeViewSs
{
get
{
return selectedItemsTreeViewSs;
}
set
{
selectedItemsTreeViewSs = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(SelectedItemsTreeViewSs)));
}
}
public ObservableCollection<VmItem> ItemsTreeViewSs
{
get { return itemsTreeViewSs; }
set
{
itemsTreeViewSs = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(ItemsTreeViewSs)));
}
}
}
最后一件事......以编程方式选择的例子: 我在MainWindow.xaml和它的处理程序上创建了一个按钮..
private void Button_Click(object sender, RoutedEventArgs e)
{
TreeViewSelectedItemExBehavior.SetSelectedItemEx(trvwSs, trvwSs.Items[3]);
//TreeViewSelectedItemExBehavior.SetSelectedItemEx(trvwSs, null);
}
希望这有助于某人:)
答案 11 :(得分:0)
你可以通过代码
来实现$(document).ready(function(){
setInterval(function(){
$('#pijl').animate({
$(this).css('margin-top', '120px');
},500);
},6000);});
答案 12 :(得分:0)
我认为这是最简单的解决方案:
private void MouseDownEventProcessing(TreeNodeMouseClickEventArgs e)
{
tvEmployeeDirectory.SelectedNode = e.Node;
}
答案 13 :(得分:0)
建议的答案不起作用。 @fandisusanto的答案可能确实有效,但是可以使其更简单。这是我能想到的最简单的答案:
private static void DeselectTreeViewItem(IEnumerable<TreeViewItem> treeViewItems)
{
foreach (var treeViewItem in treeViewItems)
{
if (treeViewItem.IsSelected)
{
treeViewItem.IsSelected = false;
return;
}
DeselectTreeViewItem(treeViewItem.Items.Cast<TreeViewItem>());
}
}
用法:
private void ClearSelectedItem()
{
if (AssetTreeView.SelectedItem != null)
{
DeselectTreeViewItem(AssetTreeView.Items.Cast<TreeViewItem>());
}
}
答案 14 :(得分:0)
这是我的解决方案。其他人以各种方式对我失败了。您需要使树从上到下走动,在每个级别上查找树项目,并一路扩展和更新布局。
此函数获取一个节点堆栈,其中堆栈中的第一个是最上面的节点,而堆栈中的每个后续节点都是前一个父节点的子节点。第二个参数是TreeView。
找到每个项目后,该项目将展开,最后一个项目将返回,调用者可以在其中选择它。
TreeViewItem FindTreeViewItem( Stack<object> nodeStack, TreeView treeView )
{
ItemsControl itemsControl = treeView;
while (nodeStack.Count > 0) {
object node = nodeStack.Pop();
bool found = false;
foreach (object item in itemsControl.Items) {
if (item == node) {
found = true;
if (itemsControl.ItemContainerGenerator.ContainerFromItem( item ) is TreeViewItem treeViewItem) {
if (nodeStack.Count == 0) {
return treeViewItem;
}
itemsControl = treeViewItem;
treeViewItem.IsExpanded = true;
treeViewItem.UpdateLayout();
break;
}
}
}
if (!found) {
return null;
}
}
return null;
}
如何调用它的示例:
// Build nodeStack here from your data
TreeViewItem treeViewItem = FindTreeViewItem( nodeStack, treeView );
if (treeViewItem != null) {
treeViewItem.IsSelected = true;
treeViewItem.BringIntoView();
}
答案 15 :(得分:0)
我为此编写了一个Helper类,该类支持MVVM和延迟加载的项目。
public class TreeViewHelper<TModel>
{
public TreeViewHelper(TreeView treeView, Func<TModel, TModel> getParent, Func<TModel, IList<TModel>> getSubItems)
{
TreeView = treeView;
GetParent = getParent;
GetSubItems = getSubItems;
}
public TreeView TreeView { get; }
public Func<TModel, TModel> GetParent { get; }
public Func<TModel, IList<TModel>> GetSubItems { get; }
public void SelectItemWhileLoaded(TModel node, IList<TModel> rootNodes)
{
if (TreeView.IsLoaded)
{
SelectItem(node, rootNodes);
}
else
{
TreeView.Loaded += TreeView_Loaded;
void TreeView_Loaded(object sender, System.Windows.RoutedEventArgs e)
{
TreeView.Loaded -= TreeView_Loaded;
SelectItem(node, rootNodes);
}
}
}
public void SelectItem(TModel node, IList<TModel> rootNodes)
{
Stack<TModel> nodes = new Stack<TModel>();
//push into stack
while (!rootNodes.Contains(node))
{
nodes.Push(node);
node = GetParent(node);
}
TreeViewItem treeViewItem = TreeView.ItemContainerGenerator
.ContainerFromItem(node) as TreeViewItem;
if (nodes.Count == 0)
{
//Top level
treeViewItem.IsSelected = true;
treeViewItem.BringIntoView();
return;
}
Expanded(true);
void Expanded(bool top)
{
if (!top)
{
treeViewItem = treeViewItem.ItemContainerGenerator
.ContainerFromItem(node) as TreeViewItem;
if (nodes.Count == 0)
{
treeViewItem.IsSelected = true;
treeViewItem.BringIntoView();
return;
}
}
node = nodes.Pop();
treeViewItem.IsExpanded = true;
if (treeViewItem.ItemContainerGenerator.Status == GeneratorStatus.ContainersGenerated)
{
Expanded(true);
}
else
{
//Lazy
treeViewItem.ItemContainerGenerator.StatusChanged += ItemContainerGenerator_StatusChanged;
}
}
void ItemContainerGenerator_StatusChanged(object sender, EventArgs e)
{
if (treeViewItem.ItemContainerGenerator.Status == GeneratorStatus.ContainersGenerated)
{
treeViewItem.ItemContainerGenerator.StatusChanged -= ItemContainerGenerator_StatusChanged;
Expanded(false);
}
}
}
}