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:
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:
public class Dummy
{
public string Subject { get; set; }
public string Body { get; set; }
public DateTime DueDateStart { get; set; }
}
Import your project namespace into XAML by adding the following import at the top:
xmlns:local="clr-namespace:YourProjectNamespace"
Now you can add items (rows) to your DataGrid at design-time like (make sure your columns have proper bindings):
<DataGrid AutoGenerateColumns="False">
<DataGrid.Columns>
<DataGridTextColumn Header="Subject" Binding="{Binding Path=Subject}"/>
<DataGridTextColumn Header="Body" Binding="{Binding Path=Body}"/>
<DataGridTextColumn Header="Due Date" Binding="{Binding Path=DueDateStart}"/>
</DataGrid.Columns>
<local:Dummy Subject="Subject 1" Body="Body 1" ... />
<local:Dummy Subject="Subject 2" Body="Body 2" ... />
</DataGrid>
Hope this helps someone!
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:
<local:TestDataList xmlns:local="clr-namespace:YourNamespaceHere" Capacity="46" ID="33" Name="Maecenas curabitur cras">
<local:TestData ID="66" Name="Aenean vestibulum class"/>
<local:TestData ID="34" Name="Duis adipiscing nunc praesent"/>
<local:TestData ID="91" Name="Accumsan bibendum nam"/>
</local:TestDataList>
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):
d:DataContext="{d:DesignData Source=SampleData/TestDataListSampleData.xaml}"
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:
public class MyListOfStrings : List<string>
{ }