【问题标题】:How to access datagrid template column textbox text WPF C#如何访问datagrid模板列文本框文本WPF C#
【发布时间】:2013-06-04 13:52:38
【问题描述】:

我需要从后面的代码访问DataGrid 的模板列中的文本,但我不知道如何。我需要将文本更改为在SelectionChanged 事件中传递给它的任何字符串。有人可以告诉我如何实现这一目标吗?我发现了一个类似的问题here 但它没有答案。

【问题讨论】:

    标签: wpf datagrid wpfdatagrid datagridtemplatecolumn


    【解决方案1】:

    要在DataGrid 模板列中查找控件,您应该使用FindChild()

        public static T FindChild<T>(DependencyObject parent, string childName) where T : DependencyObject
        {
            if (parent == null)
            {
                return null;
            }
    
            T foundChild = null;
    
            int childrenCount = VisualTreeHelper.GetChildrenCount(parent);
    
            for (int i = 0; i < childrenCount; i++)
            {
                var child = VisualTreeHelper.GetChild(parent, i);
                T childType = child as T;
    
                if (childType == null)
                {
                    foundChild = FindChild<T>(child, childName);
    
                    if (foundChild != null) break;
                }
                else
                    if (!string.IsNullOrEmpty(childName))
                    {
                        var frameworkElement = child as FrameworkElement;
    
                        if (frameworkElement != null && frameworkElement.Name == childName)
                        {
                            foundChild = (T)child;
                            break;
                        }
                        else
                        {
                            foundChild = FindChild<T>(child, childName);
    
                            if (foundChild != null)
                            {
                                break;
                            }
                        }
                    }
                    else
                    {
                        foundChild = (T)child;
                        break;
                    }
            }
    
            return foundChild;
        }
    

    例如,我在 MyDataGrid 中有这个模板列:

    <DataGridTemplateColumn Width="1.5*" IsReadOnly="False">
        <DataGridTemplateColumn.Header>
            <TextBlock Text="Sample" ToolTip="{Binding Path=Text, RelativeSource={RelativeSource Self}}" FontSize="14" />
         </DataGridTemplateColumn.Header>
    
         <DataGridTemplateColumn.CellTemplate>
             <DataTemplate>
                 <TextBlock x:Name="MyTextBlock" Text="Hello!" />
             </DataTemplate>
        </DataGridTemplateColumn.CellTemplate>
    </DataGridTemplateColumn>
    

    从代码中访问,你可以:

    TextBlock MyTextBlock = FindChild<TextBlock>(MyDataGrid, "MyTextBlock");
    
    MessageBox.Show(MyTextBlock.Text);
    

    注意:只有在控件将完全加载时才使用FindChild,否则找不到它并给出null。在这种情况下,我将此代码放在事件 ContentRendered (Window) 中,它表示窗口的所有内容都已成功加载(即使事件 MyDataGrid_Loaded 也无法访问 MyTextBlock,因为它尚未加载):

        private void Window_ContentRendered(object sender, EventArgs e)
        {
            TextBlock MyTextBlock = FindChild<TextBlock>(MyDataGrid, "MyTextBlock");
    
            MessageBox.Show(MyTextBlock.Text);
        }
    

    EDIT1:

    要访问选定行的控件,将事件 SelectionChanged 添加到 DataGrid 中起作用,这将给出选定行:

        private void MyDataGrid_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            try
            {
                var row_list = GetDataGridRows(MyDataGrid);
    
                foreach (DataGridRow single_row in row_list)
                {
                    if (single_row.IsSelected == true)
                    {
                        TextBlock MyTextBlock = FindChild<TextBlock>(single_row, "MyTextBlock");
    
                        MessageBox.Show(MyTextBlock.Text);
                    }
                }
            }
    
            catch 
            {
                throw new Exception("Can't get access to DataGridRow");
            }
        }
    

    GetDataGridRows() 的列表:

        public IEnumerable<DataGridRow> GetDataGridRows(DataGrid grid)
        {
            var itemsSource = grid.ItemsSource as IEnumerable;
    
            if (null == itemsSource)
            {
                yield return null; 
            }
    
            foreach (var item in itemsSource)
            {
                var row = grid.ItemContainerGenerator.ContainerFromItem(item) as DataGridRow;
    
                if (null != row)
                {
                    yield return row; 
                }
            }
        }
    

    EDIT2:

    为了获得 ALL 我重写了函数 FindChild() 的项目:

        public static void FindChildGroup<T>(DependencyObject parent, string childName, ref List<T> list) where T : DependencyObject
        {
            // Checks should be made, but preferably one time before calling.
            // And here it is assumed that the programmer has taken into
            // account all of these conditions and checks are not needed.
            //if ((parent == null) || (childName == null) || (<Type T is not inheritable from FrameworkElement>))
            //{
            //    return;
            //}
    
            int childrenCount = VisualTreeHelper.GetChildrenCount(parent);
    
            for (int i = 0; i < childrenCount; i++)
            {
                // Get the child
                var child = VisualTreeHelper.GetChild(parent, i);
    
                // Compare on conformity the type
                T child_Test = child as T;
    
                // Not compare - go next
                if (child_Test == null)
                {
                    // Go the deep
                    FindChildGroup<T>(child, childName, ref list);
                }
                else
                {
                    // If match, then check the name of the item
                    FrameworkElement child_Element = child_Test as FrameworkElement;
    
                    if (child_Element.Name == childName)
                    {
                        // Found
                        list.Add(child_Test);
                    }
    
                    // We are looking for further, perhaps there are
                    // children with the same name
                    FindChildGroup<T>(child, childName, ref list);
                }
            }
    
            return;
        }
    

    调用这个新函数:

       private void Window_ContentRendered(object sender, EventArgs e)
       {
            // Create the List
            List<TextBlock> list = new List<TextBlock>();
    
            // Find all elements
            FindChildGroup<TextBlock>(MyDataGrid, "MyTextBlock", ref list);
            string text = "";
    
            // Print
            foreach (TextBlock elem in list)
            {
                text += elem.Text + "\n";
            }
    
            MessageBox.Show(text, "Text in TextBlock");
       }
    

    一般来说,这种做法并不是最好的……要获取项目(例如 all 或 selected),您可以直接联系存储数据的列表(例如 ObservableCollection)。此外,它是有用的事件,例如 PropertyChanged

    【讨论】:

    • 我面临着与我链接的线程中的人相同的问题。我找不到在每一行都有效的方法。只有一个。如何让它在选定的行上工作?
    • Hmm.. 获取所有这些的代码有效,但第一次编辑的代码只是抛出了无法访问 DataGridRow 的异常
    • 我有这个异常是在控件名称错误时触发的,例如:TextBlock MyTextBlock = FindChild(single_row, "WrongNameOfTextBlock")。而当传递了错误的DataGrid,例如NullDataGrid:DataGrid NullDataGrid = null; var row_list = GetDataGridRows(NullDataGrid)。检查这些情况。
    • @AnatoliyNikolaev 但是如果您使用的是Page 而不是WindowPage 似乎没有 ContentRendered 事件。
    猜你喜欢
    • 2016-02-26
    • 1970-01-01
    • 2011-03-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多