Home > Net >  The name 'DataGrid' does not exist in the current context
The name 'DataGrid' does not exist in the current context

Time:09-22

I get this error message when trying to use a class of mine on a different xaml.cs other than the MainWindow.xaml.cs. Now my question is: How can I reference to my DataGrid in a file other than the MainWindow.xaml.cs?

CodePudding user response:

Use helper method to search for a FrameworkElement by both Type and Name..

using System.Windows;
using System.Windows.Media;

namespace My.Name.Space
{
    public static class UiHelpers
    {
        public static T GetChildOfType<T>(this FrameworkElement parent, string childName)
            where T : FrameworkElement
        {
            if (parent == null) return null;
            T child = default;
            var numVisuals = VisualTreeHelper.GetChildrenCount(parent);
            for (var i = 0; i < numVisuals; i  )
            {
                var v = VisualTreeHelper.GetChild(parent, i) as FrameworkElement;
                child = v as T ?? v.ChildOfType<T>(childName);
                if (child != null && child.Name == childName)
                    break;
            }

            return child;
        }
    }
}

In action, you give the FrameworkElement (i.e. DataGrid) a name in .xaml

<DataGrid x:Name="MyDataGrid" ...

Then you can search for it in .cs, starting from MainWindow or any other parent of the DataGrid other than the MainWindow.

var dataGrid = Application.Current.MainWindow.GetChildOfType<DataGrid>("MyDataGrid");
  • Related