Can I add WPF items programmatically without any manual interference with XAML? Please give me a hand.
Asked
Active
Viewed 78 times
1 Answers
1
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; }
}

ASh
- 34,632
- 9
- 60
- 82
-
OK, Thanks! I'm a beginner in stackoverflow. But how to add properties automatically? Let's say you give a name "B", the "B" property should be added in DgItem class programmatically. – makelot Jan 26 '22 at 11:00
-
do you mean `(myDataGrid.ItemsSource as ObservableCollection
).Add(new DgItem { Name = "B" })`? – ASh Jan 26 '22 at 11:39 -
I'm very sorry for such a slow reply, the time difference is too big. Yes, so long as to solve the problem. Your appending code works quite well ! Hotshot ! Very helpful ! Thanks a lot ! – makelot Jan 26 '22 at 23:57