【问题标题】:Get TreeViewItem From TreeView in WPF从 WPF 中的 TreeView 获取 TreeViewItem
【发布时间】:2019-09-04 22:05:31
【问题描述】:

我在从TreeViewHierarchicalDataTemplate 获取TreeViewItem 时遇到问题。我想按值搜索一个项目并将 IsExpanded 设置为 True,然后选择它。

我在 Visual Studio 2015 和 Windows 10 中使用 C# WPF。

XAML 代码:

<TreeView x:Name="TreeOres" SelectedItemChanged="TreeOres_SelectedItemChanged"  Background="#f9f9f9" MinWidth="350" Width="auto" DockPanel.Dock="Left" ItemsSource="{Binding}">
                <TreeView.ItemTemplate>
                    <HierarchicalDataTemplate DataType="local:Ores" ItemsSource="{Binding Path=resParent_Code_FK}">
                        <DockPanel LastChildFill="True" HorizontalAlignment="Stretch" Width="auto" Margin="0,5,0,5">
                            <Label Width="30" Height="30" DockPanel.Dock="Left" Uid="{Binding Path=Ores_ParentCode_FK}" Template="{StaticResource ImageTemp}"/>
                            <Label Content="{Binding Path=Ores_Name}" Width="250" DockPanel.Dock="Left"/>
                            <DockPanel.ContextMenu>
                                <ContextMenu>
                                    <MenuItem Header="اضافة مجلد جديد + " x:Name="AddGroup" Click="AddGroup_Click" Uid="{Binding Path=Ores_Code}" />
                                    <MenuItem Header="اضافة صنف جديد + " x:Name="AddItem" Click="AddItem_Click" Uid="{Binding Path=Ores_Code}" />
                                </ContextMenu>
                            </DockPanel.ContextMenu>
                        </DockPanel>
                    </HierarchicalDataTemplate>
                </TreeView.ItemTemplate>
                <TreeView.Resources>
                    <LinearGradientBrush x:Key="{x:Static SystemColors.HighlightBrushKey}" EndPoint="0,1" StartPoint="0,0">
                        <GradientStop Color="#FFD9F4FF" Offset="0"/>
                        <GradientStop Color="#FF9BDDFB" Offset="1"/>
                    </LinearGradientBrush>
                    <LinearGradientBrush x:Key="{x:Static SystemColors.ControlBrushKey}" EndPoint="0,1" StartPoint="0,0">
                        <GradientStop Color="#FFEEEDED" Offset="0"/>
                        <GradientStop Color="#FFDDDDDD" Offset="1"/>
                    </LinearGradientBrush>
                    <SolidColorBrush x:Key="{x:Static SystemColors.HighlightTextBrushKey}" Color="Black" />
                    <SolidColorBrush x:Key="{x:Static SystemColors.ControlTextBrushKey}" Color="Black" />
                    <Style TargetType="{x:Type TreeViewItem}">
                        <Setter Property="IsSelected" Value="{Binding IsSelected, Mode=TwoWay}" />
                        <Setter Property="IsExpanded" Value="True" />
                    </Style>
                </TreeView.Resources>
                <TreeView.ItemContainerStyle>
                    <Style TargetType="{x:Type TreeViewItem}">
                        <Setter Property="BorderThickness" Value="1.5"/>
                        <Style.Triggers>
                            <Trigger Property="IsSelected" Value="True">
                                <Setter Property="BorderBrush" Value="#adc6e5"/>
                            </Trigger>
                            <Trigger Property="IsSelected" Value="True">
                                <Setter Property="FontWeight" Value="Bold" />
                            </Trigger>
                            <MultiTrigger>
                                <MultiTrigger.Conditions>
                                    <Condition Property="IsSelected" Value="True"/>
                                    <Condition Property="IsSelectionActive" Value="False"/>
                                </MultiTrigger.Conditions>
                                <Setter Property="BorderBrush" Value="LightGray"/>
                            </MultiTrigger>
                        </Style.Triggers>
                        <Style.Resources>
                            <Style TargetType="Border">
                                <Setter Property="CornerRadius" Value="1"/>
                            </Style>
                        </Style.Resources>
                    </Style>
                </TreeView.ItemContainerStyle>
            </TreeView>

和 C# 代码

class ClassTreeView
{
    /// <summary>
    /// Search in treeview by some value
    /// </summary>
    /// <param name="FilterColumn"></param>
    /// <param name="FilterString"></param>
    /// <param name="FilterColumnText"></param>
    /// /// <param name="Result"></param>
    /// 
    public string FilterString { get; set; }
    public string FilterColumn { get; set; }
    public string FilterColumnText { get; set; }
    public object Result { get; set; }
    public DataTable mtable { get; set; }

    public void SelectNodeById(TreeView Tree)
    {
        for (int i = 0; i < Tree.Items.Count; i++)
        {
            DataRowView row = Tree.Items[i] as DataRowView;
            if (SearchInItem(row))
            {
                Tree.ItemsSource = null;
                Tree.ItemsSource = mtable.DefaultView;
            }
        }
    }
    private bool SearchInItem(DataRowView item)
    {
        foreach (DataRowView obje in item.DataView)
        {
            if (SeaechNode(obje))
            {
                break;
            }
            SearchInItem(obje);
        }
        return false;
    }
    private bool SeaechNode(DataRowView row)
    {
        foreach (DataRowView dr in row.DataView)
        {
            dr.DataView.RowFilter = FilterColumn + "=" + FilterString;
            if(dr != null)
            {
                return true;
            }
        }
        return false;
    }
}

【问题讨论】:

    标签: c# .net wpf treeview


    【解决方案1】:

    也许这会有所帮助: Find a WPF element inside DataTemplate in the code-behind

    否则: 为了找到该项目,您可以执行以下操作:

     public void SelectNodeById(TreeView Tree)
            {
                var item = findItemById(Tree, "uid");
            }
    
            private static object findItemById(TreeView Tree, string uid)
            {
                foreach (var item in Tree.Items)
                {
                    //every item in your tree is a dockpanel
                    var d = item as DockPanel;
    
                    //the first item has a uid
                    if (d.Children.Count > 0 && d.Children[0].Uid == uid)
                        return item;
                }
    
                return null;
            }
    

    要将项目的属性IsExpanded 更改为true,您应该将其更改为TreeViewItem。 然后你可以这样做:

    var item = new TreeViewItem();
    item.IsExpanded = true;
    item.IsSelected = true;
    

    【讨论】:

    • 谢谢你,先生,但更新代码后我有一些问题这个图像错误imgur.com/a/LtxJRLw
    • 我检查了项目类型,我得到了 'datarowview' 类型的项目
    • 感谢您回答我的问题,但我想说如果我展开树视图中的所有项目,代码是有效的,我想在自动搜索后展开项目
    • 如果我理解正确,您想从代码而不是 UI 更新项目。在这种情况下,您将不需要SelectItemChanged 事件来触发项目的扩展。如果这是真的,在这里使用这篇文章 [link] (stackoverflow.com/a/4080545/8649015) ,您应该能够将您的项目的 IsExpandable 属性与此和普通 MVVM 绑定,您可以将属性设置为您想要的任何内容
    • 您能以某种方式与我分享答案吗?也许编辑你的帖子
    【解决方案2】:

    这是完整的课程代码,您可以使用此代码:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Windows.Controls;
    using System.Data;
    using System.Windows.Media;
    using System.Windows;
    
    public string FilterString { get; set; } // Value searching
    public string FilterColumn { get; set; } // column name
    public string FilterColumnText { get; set; } // by this variable will display text
    System.Windows.Threading.DispatcherTimer tmr = new System.Windows.Threading.DispatcherTimer(); // by this timer will search about an item becouse for going to next item we need to stop sometime
    private int count = 0;
    private int i = 0;
    // will call to this method and adding treeview control to search about item
    public void FindNode(TreeView tree = null)
        {
            tmr.Interval = new TimeSpan(0, 0, 0, 0, 1);
            // will add count of objects  
            count = FindVisualChildren<DependencyObject>(tree).ToList().Count;
            tmr.Tick += (s, e) =>
            {
                if (i < count)
                {
                    if (FindVisualChildren<Grid>(tree).ToList()[i] != null)
                    {
                        Grid node = FindVisualChildren<Grid>(tree).ToList()[i];
                        if (SelectNode(node))
                        {
                            // if we found the item will stoping the timer
                            i = 0;
                            count = 0;
                            tmr.Stop();
                        }
                    }
                    i += 1;
                }
                // will add new count to the variable after expand the items
                count = FindVisualChildren<Grid>(tree).ToList().Count;
            };
            tmr.Start();
        }
    // Search for an item
    bool SelectNode(DependencyObject node)
        {
            bool fo = false;
            for (int i = 0; i < (node as Grid).Children.Count; i++)
            {
                object obj = (node as Grid).Children[i];
                if (obj.GetType() == typeof(Border))
                {
                    TreeViewItem item = ((obj as Border).TemplatedParent as TreeViewItem);
                    if (item != null && item is TreeViewItem)
                    {
                        if (item.Items.Count > 0)
                        {
                            item.IsExpanded = true;
                        }
                        var row = item.Header as DataRowView;
                        if (row[FilterColumn].ToString() == FilterString)
                        {
                            item.IsSelected = true;
                            BindParent(item);
                            fo = true;
                            break;
                        }
                        items.Add(item);
                    }
                }
            }
            return fo;
        }
        public IEnumerable<T> FindVisualChildren<T>(DependencyObject depObj) where T : DependencyObject
        {
            if (depObj != null)
            {
                for (int i = 0; i < VisualTreeHelper.GetChildrenCount(depObj); i++)
                {
                    DependencyObject child = VisualTreeHelper.GetChild(depObj, i);
    
                    if (child != null && child is T)
                        yield return (T)child;
    
                    foreach (T childOfChild in FindVisualChildren<T>(child))
                        yield return childOfChild;
                }
            }
        }
    

    如果我想提供帮助,我随时待命

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-08-23
      • 2011-07-10
      • 2015-12-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多