Sunday, April 12, 2015

Annoying Last Empty Row on WPF DataGrid



<Window x:Class="AnnoyingDataGridExtraRow.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525"
        Name="ThisWindow">

    <DataGrid ItemsSource="{Binding ElementName=ThisWindow, Path=MyModels}" AutoGenerateColumns="False">
        <DataGrid.Columns>
            <DataGridTextColumn Header="Strings" Binding="{Binding Text}" />
            <DataGridTextColumn Header="Doubles" Binding="{Binding Value}" />
        </DataGrid.Columns>
    </DataGrid>
</Window>

public partial class MainWindow : Window
{
    public MainWindow()
    {
        MyModels = new List<MyModel>
        {
            new MyModel { Text = "AAA", Value = 0.423 },
            new MyModel { Text = "BBB", Value = 0.315 },
            new MyModel { Text = "CCC", Value = 4.422 }
        };

        InitializeComponent();
    }

    public List<MyModel> MyModels { get; set; }
}
public class MyModel
{
    public string Text { get; set; }

    public double Value { get; set; }
}

If we don't specify a constructor, WPF DataGrid will default to an empty constructor, which allow users to add new row to the grid.

If I change MyModel to something like this:

public class MyModel
{
    public MyModel(string text, double value)
    {
        Text = text;
        Value = value;
    }

    public string Text { get; set; }

    public double Value { get; set; }
}

...then that extra row disappears.

If we want to make the DataGrid readonly, make sure we don't specify an empty constructor. Otherwise we need to set CanUsersAddRows to False.

No comments:

Post a Comment