C# 从WPF中的TreeView获取TreeView项

C# 从WPF中的TreeView获取TreeView项,c#,.net,wpf,treeview,C#,.net,Wpf,Treeview,使用hierarchycaldatatemplate从TreeView获取treevieItem时遇到问题。我想按值搜索一个项目,并将IsExpanded设置为True,然后选择它 我正在Visual Studio 2015和Windows 10中使用C#WPF XAML代码: <TreeView x:Name="TreeOres" SelectedItemChanged="TreeOres_SelectedItemChanged" Background="#f9f9f9" MinWid

使用
hierarchycaldatatemplate
TreeView
获取
treevieItem
时遇到问题。我想按值搜索一个项目,并将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#代码

类ClassTreeView
{
/// 
///按某个值在treeview中搜索
/// 
/// 
/// 
/// 
/// /// 
/// 
公共字符串筛选器字符串{get;set;}
公共字符串筛选器列{get;set;}
公共字符串筛选器ColumnText{get;set;}
公共对象结果{get;set;}
公共数据表mtable{get;set;}
public void SelectNodeById(树视图树)
{
对于(int i=0;i
也许这会有帮助:

否则: 为了找到物品,你可以这样做:

 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;

这是完整的类代码。您可以使用此代码:

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;
            }
        }
    }
使用系统;
使用System.Collections.Generic;
使用System.Linq;
使用系统文本;
使用System.Threading.Tasks;
使用System.Windows.Controls;
使用系统数据;
使用System.Windows.Media;
使用System.Windows;
公共字符串筛选器字符串{get;set;}//值搜索
公共字符串过滤器column{get;set;}//列名
公共字符串过滤器ColumnText{get;set;}///由此变量将显示文本
System.Windows.Threading.dispatchermer tmr=新系统.Windows.Threading.dispatchermer();//通过此计时器,我们将搜索一个项目,因为我们需要在某个时间停止下一个项目
私有整数计数=0;
私有整数i=0;
//将调用此方法并添加treeview控件以搜索关于项目
public void FindNode(TreeView tree=null)
{
tmr.Interval=新的时间跨度(0,0,0,0,1);
//将添加对象的计数
count=FindVisualChildren(tree).ToList().count;
tmr.勾选+=(s,e)=>
{
如果(i0)
{
item.IsExpanded=true;
}
var row=项目。标题为DataRowView;
if(行[FilterColumn].ToString()==FilterString)
{
item.IsSelected=true;
家长(项目);
fo=真;
布雷
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;
            }
        }
    }