The sequence is as follows:
1) Move the code from the MainWindow class to the user class and set the DataContext property:
public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); this.DataContext = new MainWindowViewModel(); } } public class MainWindowViewModel { public MainWindowViewModel() { myData = new List<Item> { new Item{ Id=5, Description="Brown Car", Title="my car"}, new Item{Id=1,Description="sweet dog", Title="my dog"}, }; } public List<Item> MyData { get { return myData; } } List<Item> myData; }
2) Change the DataGrid binding:
ItemsSource="{Binding MyData}"
3) Add a new ResourceDictionary named DataGridSample.xaml , open its properties (Right-click → Properties), set the BuildAction property to DesignData and clear the value of the CustomTool property.
4) Copy this code, but change the vm namespace from WpfApplication1 to yours:
<vm:MainWindowViewModel xmlns:vm="clr-namespace:WpfApplication1"> <vm:MainWindowViewModel.MyData> <vm:Item Id="1" Title="My dog" Description="Sweet dog" /> <vm:Item Id="5" Title="My car" Description="Brown car" /> </vm:MainWindowViewModel.MyData> </vm:MainWindowViewModel>
5) Go back to MainWindow.xaml and add the following lines to the Window element, where all the declarations are:
xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d" d:DataContext="{d:DesignData Source=DataGridSample.xaml}"
After that, you can switch to development mode, and you will see that the datagrid is with two rows.
source share