WPF - fill data on data grid

谁说我不能喝 提交于 2019-12-06 12:10:08

Assign users (collection) as a ItemsSource of DataGrid to display the data on datagrid.

XAML

<Window x:Class="WpfApplication1.Window1"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="Window1" Height="300" Width="500">
    <StackPanel>
        <Grid x:Name="Grid" Background="#FF1BA1E2">
            <DataGrid x:Name="DataGrid" HorizontalAlignment="Left" Margin="65,10,0,0" VerticalAlignment="Top" Height="180" Width="385" SelectionChanged="DataGrid_SelectionChanged_1"/>
            <Button Content="Button" HorizontalAlignment="Left" Margin="95,235,0,0" VerticalAlignment="Top" Width="75" Height="30" Click="Button_Click_1"/>
        </Grid>
    </StackPanel>
</Window>

Code behind

//Fill data here
private void Button_Click_1(object sender, RoutedEventArgs e)
{

            ObservableCollection<User> users = new ObservableCollection<User>();
            users.Add(new User{FirstName = "firstname-1",LastName = "lastname-1"});
            users.Add(new User{FirstName = "firstname-2",LastName = "lastname-2"});
            users.Add(new User{FirstName = "firstname-3",LastName = "lastname-3"});
            users.Add(new User{FirstName = "firstname-4",LastName = "lastname-4"});
            DataGrid.ItemsSource = users;
}

That's it.

Alternatively you can define a collection property and bind it to DataGrid, instead of setting datagrid ItemsSource property from codebehind.

First define a collection property:

// Implement INotifyPropertyChanged interface correctly in this class
public ObservableCollection<User> Users { get; set; } 

Get your data and fill this collection in response to the Button.Click:

foreach (User user in users)
{
    Users.Add(user);
}

Now Bind it to the XAML:

<DataGrid ItemsSource="{Binding Users}" />

That's it! When working with WPF, just forget about doing it dynamically... that's WinForms style.


UPDATE >>>

The simplest (but not optimal) way for a beginner to get this working is to define your properties and implement the INotifyPropertyChanged interface in the code behind of the MainWindow.xaml file. Next, add this into the constructor:

public MainWindow()
{
    DataContext = this;
}

Ok, that's really it this time! :)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!