简体   繁体   中英

Binding custom object list to datagrid

I have a class

public class ServerList
{
    public ServerList(string ipAdress, int port)
    {
        IPAdress = ipAdress;
        Port = port;
    }

    public string IPAdress { get; private set; }
    public int Port { get; private set; }
}

In a second class called AddServerWindow I have a list with ServerList objects

public ObservableCollection<ServerList> ServerLists = new ObservableCollection<ServerList>(); 

How can I bind it to datagrid placed on mainwindow. I'm trying smth like this: In MainWindow.cs

DataContext = new
        {
            dump = this,
            server = new AddServerWindow(),
        };

In MainWindow.xaml

<DataGridTextColumn Header="Server" IsReadOnly="True" Width="*" Binding="{Binding server.IPAdress}"></DataGridTextColumn>
<DataGridTextColumn Header="Port" IsReadOnly="True" Width="0.6*" Binding="{Binding server.Port}"></DataGridTextColumn>

After changed to code below, DataGrid is still empty but it now have 10 columns

ItemsSource="{Binding Source=ServerLists}"

You need to bind the ItemsSource of the DataGrid. Once you do that, the DataContext for each row is a ServerList, so you can bind the columns directly to IPAdress and Port. Try something like this:

<DataGrid ItemsSource="{Binding server.ServerLists}" AutoGenerateColumns="False">
    <DataGrid.Columns>
       <DataGridTextColumn Header="Server" IsReadOnly="True" Width="*" Binding="{Binding IPAdress}"/>
       <DataGridTextColumn Header="Port" IsReadOnly="True" Width="0.6*" Binding="{Binding Port}"/>
    </DataGrid.Columns>
</DataGrid>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM