C# WPF:从DataGrid.RowDetailsTemplate获取指定控件的所有列表

C# WPF:从DataGrid.RowDetailsTemplate获取指定控件的所有列表,c#,wpf,xaml,datagrid,C#,Wpf,Xaml,Datagrid,我有mainDataGrid用于显示文档列表。 此MainGrid在XAML中指定了DataGrid.RowDetailsTemplate 此DataGrid.RowDetailsTemplate包含一个或多个(内部或嵌套)DataGrids 因此,MainGrid的每一行都包含DataGrid.RowDetailsTemplate和内部DataGrid 我需要获取所有内部(嵌套的)DataGrids的列表,其中只有MainGrid引用。 我已经尝试了Visual/Logil树帮助程序,但对于G

我有main
DataGrid
用于显示文档列表。 此
MainGrid
XAML
中指定了
DataGrid.RowDetailsTemplate

DataGrid.RowDetailsTemplate
包含一个或多个(内部或嵌套)
DataGrid
s

因此,
MainGrid
的每一行都包含
DataGrid.RowDetailsTemplate
和内部
DataGrid

我需要获取所有内部(嵌套的)
DataGrid
s的列表,其中只有
MainGrid
引用。 我已经尝试了Visual/Logil树帮助程序,但对于GetChildren调用,它们都不返回任何结果

DataGrid.RowDetails
获取嵌套的
DataGrid
的方法是什么

复制步骤: 1) 在Visual Studio 2013或更高版本中创建Windows桌面->WPF应用程序(空) 2) 使用下面的代码示例:

MainWindow.xaml

<Window x:Class="ExampleNestedGrid.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Grid>

        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>

        <ToolBar Grid.Row="0" Header="Action:">
            <Button x:Name="RefreshBtn" Command="{Binding RefreshCommand}">Refresh</Button>
        </ToolBar>

        <DataGrid x:Name="MainGrid" ItemsSource="{Binding Documents}" AutoGenerateColumns="False" Grid.Row="1">
            <DataGrid.Columns>
                <DataGridTextColumn Binding="{Binding Name, Mode=OneWay}" Width="*"/>
                <DataGridTextColumn Binding="{Binding Number, Mode=OneWay}" Width="*"/>
            </DataGrid.Columns>

            <DataGrid.RowDetailsTemplate>
                <DataTemplate>
                    <Grid>
                        <DataGrid x:Name="NestedGrid" ItemsSource="{Binding LinkedEmployees}" AutoGenerateColumns="False">
                            <DataGrid.Columns>
                                <DataGridTextColumn Binding="{Binding Id, Mode=OneWay}" Width="150"/>
                                <DataGridTextColumn Binding="{Binding Name, Mode=OneWay}" Width="150"/>
                                <DataGridTextColumn Binding="{Binding Status, Mode=OneWay}" Width="150"/>
                            </DataGrid.Columns>
                        </DataGrid>
                    </Grid>
                </DataTemplate>
            </DataGrid.RowDetailsTemplate>
        </DataGrid>
    </Grid>
</Window>

刷新
MainWindow.xaml.cs

using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Runtime.CompilerServices;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;

namespace ExampleNestedGrid
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();

            DataContext = new DisplayViewModel(MainGrid);
        }
    }

    public class DisplayViewModel : PropertyBase
    {
        private DataGrid MainGrid;

        public DisplayViewModel(DataGrid MainGrid) 
        {
            this.MainGrid = MainGrid;

            Documents = new ObservableCollection<Document>();
            LinkedEmployee empl1 = new LinkedEmployee("1", "Ben");
            LinkedEmployee empl2 = new LinkedEmployee("2", "John");

            Document doc = new Document("first", "111");
            doc.LinkedEmployees.Add(empl1);
            doc.LinkedEmployees.Add(empl2);

            Documents.Add(doc);

            RefreshCommand = new RefreshCommand(Documents, MainGrid);
        }

        public ObservableCollection<Document> Documents { get; set; }
        public ICommand RefreshCommand { get; set; }
    }

    public sealed class LinkedEmployee : PropertyBase
    {
        public LinkedEmployee(string id, string name)
        {
            _id = id;
            _name = name;
        }

        public void Update(string name)
        {
            Name = name;
        }

        private string _id;
        private string _name;
        private bool _status;

        public bool Status 
        {
            get { return _status; }
            set
            {
                _status = value;
                OnPropertyChanged();
            }
        }

        public string Id
        {
            get { return _id; }
            set
            {
                _id = value;
                OnPropertyChanged();
            }
        }

        public string Name
        {
            get { return _name; }
            set
            {
                _name = value;
                OnPropertyChanged();
            }
        }
    }

    public class Document : PropertyBase
    {
        public Document(string name, string number)
        {
            _name = name;
            _number = number;

            LinkedEmployees = new ObservableCollection<LinkedEmployee>();
        }

        public void Update(string number)
        {
            Number = number;
        }

        private string _name;
        private string _number;

        public virtual string Name
        {
            get { return _name; }
            set
            {
                _name = value;
                OnPropertyChanged();
            }
        }

        public virtual string Number
        {
            get { return _number; }
            set
            {
                _number = value;
                OnPropertyChanged();
            }
        }

        public ObservableCollection<LinkedEmployee> LinkedEmployees { get; set; }
    }

    public abstract class PropertyBase : INotifyPropertyChanged
    {
        #region public properties
        public event PropertyChangedEventHandler PropertyChanged;
        #endregion

        #region protected methods
        protected void OnPropertyChanged([CallerMemberName]string caller = null)
        {
            if (PropertyChanged != null)
                PropertyChanged.Invoke(this, new PropertyChangedEventArgs(caller));
        }
        #endregion
    }
}
使用System.Collections.ObjectModel;
使用系统组件模型;
使用System.Runtime.CompilerServices;
使用System.Windows;
使用System.Windows.Controls;
使用System.Windows.Input;
命名空间示例NestEdGrid
{
/// 
///MainWindow.xaml的交互逻辑
/// 
公共部分类主窗口:窗口
{
公共主窗口()
{
初始化组件();
DataContext=新的DisplayViewModel(主网格);
}
}
公共类DisplayViewModel:PropertyBase
{
私有数据网格主网格;
公共显示视图模型(DataGrid主网格)
{
this.MainGrid=MainGrid;
文档=新的ObservableCollection();
LinkedEmployee Employee 1=新的LinkedEmployee(“1”,“Ben”);
LinkedEmployee Employee 2=新的LinkedEmployee(“2”,“John”);
文件文件=新文件(“第一”、“111”);
doc.LinkedEmployees.Add(employ1);
doc.LinkedEmployees.Add(employ2);
文件。添加(doc);
RefreshCommand=新的RefreshCommand(文档,主网格);
}
公共可观察收集文档{get;set;}
公共ICommand刷新命令{get;set;}
}
公共密封类LinkedEmployee:PropertyBase
{
公共LinkedEmployee(字符串id、字符串名称)
{
_id=id;
_名称=名称;
}
公共无效更新(字符串名称)
{
名称=名称;
}
私有字符串_id;
私有字符串\u名称;
私人住房状况;
公共布尔状态
{
获取{return\u status;}
设置
{
_状态=价值;
OnPropertyChanged();
}
}
公共字符串Id
{
获取{return\u id;}
设置
{
_id=值;
OnPropertyChanged();
}
}
公共字符串名
{
获取{return\u name;}
设置
{
_名称=值;
OnPropertyChanged();
}
}
}
公共类文档:PropertyBase
{
公共文档(字符串名称、字符串编号)
{
_名称=名称;
_数字=数字;
LinkedEmployees=新的ObservableCollection();
}
公共无效更新(字符串编号)
{
数字=数字;
}
私有字符串\u名称;
私有字符串_编号;
公共虚拟字符串名
{
获取{return\u name;}
设置
{
_名称=值;
OnPropertyChanged();
}
}
公共虚拟字符串号
{
获取{return\u number;}
设置
{
_数字=数值;
OnPropertyChanged();
}
}
公共可观察集合LinkedEmployees{get;set;}
}
公共抽象类PropertyBase:INotifyPropertyChanged
{
#区域公共财产
公共事件属性更改事件处理程序属性更改;
#端区
#区域保护方法
受保护的void OnPropertyChanged([CallerMemberName]字符串调用者=null)
{
if(PropertyChanged!=null)
调用(这是新的PropertyChangedEventArgs(调用方));
}
#端区
}
}
RefreshCommand.cs

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Input;
using System.Windows.Media;

namespace ExampleNestedGrid
{
    public class RefreshCommand : ICommand
    {
        private ObservableCollection<Document> Documents;
        private System.Windows.Controls.DataGrid MainGrid;

        #region public methods
        public event EventHandler CanExecuteChanged
        {
            add { CommandManager.RequerySuggested += value; }
            remove { CommandManager.RequerySuggested -= value; }
        }
        #endregion

        #region public methods

        public RefreshCommand(ObservableCollection<Document> Documents, System.Windows.Controls.DataGrid MainGrid)
        {
            // TODO: Complete member initialization
            this.Documents = Documents;
            this.MainGrid = MainGrid;
        }

        public void Execute(object parameter)
        {
            Documents.First().LinkedEmployees.First().Status = !Documents.First().LinkedEmployees.First().Status;

            ICollectionView view = CollectionViewSource.GetDefaultView(Documents);
            view.Filter = (item) => item != null;

            MainGrid.ItemsSource = view;

            var childGrids = FindVisualChildren<DataGrid>(MainGrid);
            foreach (DataGrid childGrid in childGrids)
            {
                MessageBox.Show(childGrid.Name);
            }
        }

        public bool CanExecute(object parameter)
        {
            return Documents != null && MainGrid != null;
        }
        #endregion

        private static 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.Collections.ObjectModel;
使用系统组件模型;
使用System.Linq;
使用系统文本;
使用System.Windows;
使用System.Windows.Controls;
使用System.Windows.Data;
使用System.Windows.Input;
使用System.Windows.Media;
命名空间示例NestEdGrid
{
公共类刷新命令:ICommand
{
私人收集文件;
private System.Windows.Controls.DataGrid主网格;
#区域公共方法
公共事件事件处理程序CanExecuteChanged
{
添加{CommandManager.RequerySuggested+=value;}
删除{CommandManager.RequerySuggested-=value;}
}
#端区
#区域公共方法
公共刷新命令(ObservableCollection文档,System.Windows.Controls.DataGrid MainGrid)
{
//TODO:完成成员初始化
本文件=文件;
private void Button_Click(object sender, RoutedEventArgs e)
{
    var childGrids = FindVisualChildren<DataGrid>(MainGrid);
    foreach (DataGrid childGrid in childGrids)
    {
        //...
    }
}

private static 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;
            }
        }
    }
}
public void Execute(object parameter)
{
    Documents.First().LinkedEmployees.First().Status = !Documents.First().LinkedEmployees.First().Status;

    ICollectionView view = CollectionViewSource.GetDefaultView(Documents);
    view.Filter = (item) => item != null;

    MainGrid.ItemsSource = view;
    MainGrid.UpdateLayout();

    List<DataGrid> childGrids = new List<DataGrid>();
    foreach (var item in MainGrid.Items)
    {
        var container = MainGrid.ItemContainerGenerator.ContainerFromItem(item) as DataGridRow;
        if (container != null)
        {
            childGrids.AddRange(FindVisualChildren<DataGrid>(container));
        }
    }
}