简体   繁体   中英

C# WPF - Can't bind list items to gridview columns

I'm trying to load a list with multiple properties into a gridview column in a listview. I did setup a model class, pulled network adapters into a list and also wrote down the binding in the xaml code. It's still not working.

I probobaly forgot to implement a step or used the wrong logic. Also I tried to look into other threads, but none of them seemed to fix the issue I have. Thanks for your help.

.xaml

<ListView Grid.Column="0" Grid.ColumnSpan="2" Width="auto" Margin="10" Name="ListView">
  <ListView.View>
    <GridView AllowsColumnReorder="true" x:Name="GridView">
      <GridViewColumn Header="Name" Width="auto" DisplayMemberBinding="{Binding Name}"/>
     <GridViewColumn Header="Interface" Width="auto" DisplayMemberBinding="{Binding Interface}"/>
      <GridViewColumn Header="Status" Width="auto" DisplayMemberBinding="{Binding Status}"/>
    </GridView>
  </ListView.View>
</ListView >

window.xaml.cs

public MainWindow()
{
  InitializeComponent();
  List<Netadapter> adapters = new List<Netadapter>();
  foreach (NetworkInterface netadapter in NetworkInterface.GetAllNetworkInterfaces())
  {
    Netadapter adapter = new Netadapter(netadapter.Name, netadapter.Description, netadapter.OperationalStatus.ToString());
    adapters.Add(adapter);
  }
  this.DataContext = this;
}

Netadapter.cs (model)

public class Netadapter
{
  public string Name { get; set; }
  public string Interface { get; set; }
  public string Status { get; set; }

  public Netadapter(string _name, string _interface, string _status)
  {
    this.Name = _name;
    this.Interface = _interface;
    this.Status = _status;
  }
}

Your ListView needs to reference the list of Netadapters .

First of all, make the list of adapters a public property:

public MainWindow()
{
    InitializeComponent();
    Adapters = new ObservableCollection<Netadapter>();
    // Add adapters
    this.DataContext = this;
}

public ObservableCollection<Netadapter> Adapters { get; set; }

Second, bind the public propery to the ListViews ItemsSource :

<ListView Grid.Column="0" Grid.ColumnSpan="2" Width="auto" Margin="10" Name="ListView" ItemsSource="{Binding Adapters}" >

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