当前位置: 动力学知识库 > 问答 > 编程问答 >

wpf - avoid creating empty row in datagrid

问题描述:

I'm having two classes Cricket, Football and List of Observable collections of type object. Based on certain condition I want to add the object of type Cricket/Football to Observable Collection. I'm not assigning any data i.e just creating and instance of class Cricket/Football and adding that instance to Observable Collections and binding to UI. My expectation is, as I'm not assigning any data to the instance of Cricket/Football, only header has to create in the datagrid. But what I found was a row with the default value of the variables defined under the respective class along with the row header as I'm creating the instance of that class. How shall I avoid creating void row where my datagrid header is unaffected.

<DataGrid SelectionMode="Single" VerticalAlignment="Stretch" ItemsSource="{Binding itemSource, UpdateSourceTrigger=PropertyChanged}" CanUserReorderColumns="False" CanUserAddRows="False" IsReadOnly="True" CanUserDeleteRows="False" CanUserResizeColumns="False" HorizontalGridLinesBrush="Black" VerticalGridLinesBrush="Black" HorizontalScrollBarVisibility="Disabled" VerticalScrollBarVisibility="Disabled" />

Edit

网友答案:

I think your datagrid's CanUserAddRows property is set to true. Just set it to false to fix your issue.

CanUserAddRows="false"
IsReadOnly="True"

EDIT : Sorry. I read your question properly right now. Its because the ObservableCollections type is object. I will show you a small sample so that you understand how binding works in a datagrid. Your collection should have public properties, so datagrid could bind columns to it. If you use collection type of Object than you have no properies for binding, so the empty rows will be displayed.

XAML :.

<DataGrid AutoGenerateColumns="False" Height="253" HorizontalAlignment="Left" Margin="27,24,0,0" Name="dataGrid1" VerticalAlignment="Top" Width="448">
            <DataGrid.Columns>
                <DataGridTextColumn Header="First" Binding="{Binding Path=Field, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />
            </DataGrid.Columns>
 </DataGrid>

Code behind :

public partial class MainWindow : Window 
{ 
    public ObservableCollection dataSource;
    public MainWindow()
    {
        InitializeComponent();

        this.dataSource = new ObservableCollection<SomeDataSource>();

        this.dataSource.Add(new SomeDataSource { Field = "123" });
        this.dataSource.Add(new SomeDataSource { Field = "1234" });
        this.dataSource.Add(new SomeDataSource { Field = "12345" });

        this.dataGrid1.ItemsSource = this.dataSource;
    }
}

public class SomeDataSource
{
    public string Field {get;set;}
}
分享给朋友:
您可能感兴趣的文章:
随机阅读: