Search code examples
c#wpfxamlcode-behindequivalent

What is the code-behind equivalence of XAML <DataGrid Name="myDataGrid"/>?


Can I add WPF items programmatically without any manual interference with XAML? Please give me a hand.


Solution

  • learning xaml markup is necessary step in wpf development, but yes, wpf app can be written purely in c#:

    public class MainWindow : Window
    {
        DataGrid myDataGrid;
    
        public MainWindow()
        {
            InitializeComponent();
    
            var root = new Grid();
    
            myDataGrid = new DataGrid();
            var items = new ObservableCollection<DgItem> { new DgItem { Name = "A" } };
            myDataGrid.ItemsSource = items;
    
            root.Children.Add(myDataGrid);
            this.Content = root;
        }
    }
    
    public class DgItem
    {
        public string Name { get; set; }
    }