Tuesday, January 29, 2013

Styleless WPF DataGrid

I needed a plain grid that shows the items of a list. Doing it with a DataGrid I didn't have to make a custom control that adds rows to the grid trough a for cycle.






MainWindow.xaml:
<Window x:Class="WpfApplication5.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow"
        Height="200"
        Width="300"
        Background="#eee">
    <StackPanel VerticalAlignment="Top">
        <DataGrid ItemsSource="{Binding}"
                  AutoGenerateColumns="False"
                  IsReadOnly="true"
                  Background="Transparent"
                  RowBackground="Transparent"
                  GridLinesVisibility="None"
                  HeadersVisibility="None"
                  ScrollViewer.HorizontalScrollBarVisibility="Hidden"
                  BorderThickness="0">
            <DataGrid.Resources>
                <Style TargetType="DataGridCell">
                    <Setter Property="IsHitTestVisible"
                            Value="False"/>
                    <Setter Property="Focusable"
                            Value="False"/>
                </Style>
            </DataGrid.Resources>
            <DataGrid.Columns>
                <DataGridTextColumn Binding="{Binding FirstName}"/>
                <DataGridTextColumn MinWidth="0"
                                    Width="*"/>
                <DataGridTextColumn Binding="{Binding LastName}"/>
                <DataGridTextColumn MinWidth="0"
                                    Width="*"/>
                <DataGridTextColumn Binding="{Binding Age}"/>
                <DataGridTextColumn MinWidth="0"
                                    Width="*"/>
            </DataGrid.Columns>
        </DataGrid>
        <Button>DoNothing</Button>
    </StackPanel>
</Window>
MainWindow.xaml.cs:
using System.Collections.Generic;
using System.Windows;

namespace WpfApplication5
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            DataContext = new List<Employee>()
            {
                new Employee("VeryVeryLongFirstName1", "LastName1", 10),
                new Employee("FirstName2", "LastName2", 20),
                new Employee("FirstName3", "LastName3", 30)
            };
        }
    }

    public class Employee
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public int Age { get; set; }

        public Employee(string firstName, string lastName, int age)
        {
            FirstName = firstName;
            LastName = lastName;
            Age = age;
        }
    }
}