Is it possible to add one or more rows to WPF DataGrid through XAML, without binding it to a collection. What I'm looking for would essentially be something like:
<DataGrid AutoGenerateColumns="False">
<DataGrid.Columns>
...
</DataGrid.Columns>
<DataGrid.Items>
<DataGridRow>
...
</DataGridRow>
</DataGrid.Items>
</DataGrid>
I'm going to use it at design-time to see how my DataGrid columns would look like without actually running the code.
Best Answer
Feeling lucky. Found it myself. Here's the simplest way.
Create a dummy class with the same public properties (important that you define members as properties and not fields). For example:
Import your project namespace into XAML by adding the following import at the top:
Now you can add items (rows) to your DataGrid at design-time like (make sure your columns have proper bindings):
Hope this helps someone!
Update
Since this is now a popular post, I thought I should update this with the standard way of doing things.
WPF supports a concept known as Design-Time Data that serves this exact purpose. A few key advantages of using Design-Time Data over the approach I mentioned above include:
Here are the steps to create design-time data files:
DataContext
.Blend will create an XML file with sample data automatically filled in for you. The file will look something like this:
Important to note that you do not need Blend to generate this file. You can do this by hand too.
Now in your DataGrid (or whatever control you're working with), add the following property (change file path according to your project):
ItemsSource
,Columns
etc.), sample data will start showing in the designer immediately.Just for completion, note that Blend cannot generate automatic data for generic classes. For example, if your VM class contains a property of type
List<string>
(or if the VM class itself is a generic class), you'll not see that property getting generated in the sample data file. In that case, you must create your own dummy class inheriting from the generic class and then use it as the type of your property. For example: