Search code examples
wpfxamldatagridwpfdatagrid

Can static data for Datagrid rows be defined purely in XAML i.e. no code behind?


I have static data that I want to display in Datagrid format. The values are for display purposes only and will not change. Can it be added as some kind of subtag of the Datagrid control so I can avoid anything in the codebehind?

It has to be Datagrid control only as the purpose is to experiment with and demo certain Datagrid UI features with dummy blah blah content.

If pure XAML content is not possible then what is the best (quick & dirty) method to set up dummy content for a datagrid? Can it be done without writing classes etc?


Solution

  • Check the example section on this MSDN page

    Since the datagrid uses ItemsControl similar to Combobox or ListBox, datagrid should be the same logic. In that example they basically create a whole collection of objects in pure XAML.

    <XmlDataProvider x:Key="Employees" XPath="/Employees/*">
      <x:XData>
        <Employees xmlns="">
          <Employee Name="Terry Adams" Type="FTE" EmployeeNumber="1" />
          <Employee Name="Claire O&apos;Donnell" Type="FTE" EmployeeNumber="12345" />
          <Employee Name="Palle Peterson" Type="FTE" EmployeeNumber="5678" />
          <Employee Name="Amy E. Alberts" Type="CSG" EmployeeNumber="99222" />
          <Employee Name="Stefan Hesse" Type="Vendor" EmployeeNumber="-" />
        </Employees>
      </x:XData>
    </XmlDataProvider>
    
    <DataTemplate x:Key="EmployeeItemTemplate">
      <TextBlock Text="{Binding XPath=@Name}" />
    </DataTemplate>
    
    
    ...
    
    <ListBox Name="employeeListBox"
             ItemsSource="{Binding Source={StaticResource Employees}}"
             ItemTemplate="{StaticResource EmployeeItemTemplate}"
             SelectedValue="12345"
             SelectedValuePath="@EmployeeNumber"/>
    
    <TextBlock Text="{Binding ElementName=employeeListBox, 
                      Path=SelectedValue}"/>