Home > Blockchain >  Display elements of a list in C# in a WPF ListView
Display elements of a list in C# in a WPF ListView

Time:12-02

I am retrieving data from a SQL database table with an API and I am getting the data from this table in a list variable in C#. I am now trying to display the list in a ListView in a WPF window but I am not very sure how to do this. I am struggling to bind the elements of the list to the columns of the ListView. Here is my code: XAML code: `

<ListView HorizontalAlignment="Stretch"  HorizontalContentAlignment="Stretch"
                MinWidth="80"  MinHeight="25"   ItemsSource="{Binding Items}"  >
                <ListView.View>
                    <GridView>
                        <GridViewColumno Header="Code" DisplayMemberBinding="{Binding Code}" Width="100"/>
                        <GridViewColumn Header="Event" DisplayMemberBinding="{Binding Event}" Width="100"/>
                        <GridViewColumn Header="DateEntry" DisplayMemberBinding="{Binding DateEntry}" Width="100"/>
                        <GridViewColumn Header="Date Exit" DisplayMemberBinding="{Binding DateExit}" Width="100"/>
                        <GridViewColumn Header="Door Entry" DisplayMemberBinding="{Binding DoorEntry}" Width="100"/>
                        <GridViewColumn Header="Door Exit" DisplayMemberBinding="{Binding DoorExit}" Width="100"/>
                    </GridView>
                </ListView.View>
            </ListView>

C# code:

public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            MyList = new List<Acceso>();
        }

        public void GetTable_Click(object sender, RoutedEventArgs e) //this is a  button
        {

            var client = new RestClient("http://the api of my computer and port");
            var request = new RestRequest("GetAccesos", Method.Get);
            var Response = client.Execute(request);

            if (Response.StatusCode == System.Net.HttpStatusCode.OK)
            {
                //this is the list I retrieve from my SQL table
                var myList = JsonConvert.DeserializeObject<List<Information>>(Response.Content);  
            }
        }

        public class Information
        {
            public string Code{ get; set; }
            public string Event{ get; set; }
            public DateTime? DateEntry{ get; set; }
            public DateTime? DateExit{ get; set; }
            public string DoorEntry{ get; set; }
            public string DoorExit{ get; set; }

        }
    }
}

` I would like to show the elements of my list that I retreive from the SQL table and that is stored into the myList variable into a WPF ListView, but I am not very sure how to do this. The binding is not working properly.

Already explained above

CodePudding user response:

You're actually really close. You can choose to either use binding or directly set the ItemsSource of your list. I'll cover both options:

Directly settings the ItemsSource

In your XAML, remove the ItemsSource binding and give your ListView a name, this allows us to reference it directly in the code-behind:

<ListView HorizontalAlignment="Stretch"  HorizontalContentAlignment="Stretch"
                MinWidth="80"  MinHeight="25" Name="MyListView" >

Then in your code behind, after you deserialize data into a list of Information, set it directly to the itemssource:

if (Response.StatusCode == System.Net.HttpStatusCode.OK)
{
  //this is the list I retrieve from my SQL table
  var myList = JsonConvert.DeserializeObject<List<Information>>(Response.Content);  
  this.MyListView.ItemsSource = myList;
}

That should be enough to make it just work.

Using binding

Typically when you use binding you'll use a ViewModel that implements INotifyPropertyChanged (read up on MVVM for more information about this), but for simplicity of explanation, we can just make the Window class do this.

So update your window to implement INotifyPropertyChanged:

public partial class MainWindow : Window, INotifyPropertyChanged

and then add the property changed event handler and invocation function:

public event PropertyChangedEventHandler? PropertyChanged;

protected virtual void OnPropertyChanged([CallerMemberName] string? propertyName = null)
{
    PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}

This will allow you to raise property changed on properties when they change, which is how XAML bindings know to update the UI.

Now you need to add a List<Information> property which can be bound to the UI:

public List<Information> Items {get;set;}

Then when you get your list, you set it equal to your public property and notify property changed.

if (Response.StatusCode == System.Net.HttpStatusCode.OK)
{
  //this is the list I retrieve from my SQL table
  var myList = JsonConvert.DeserializeObject<List<Information>>(Response.Content);  
  Items = myList;
  OnPropertyChanged(nameof(Items));
}

Now, because in your XAML you're already binding to the property Items, you just need to make sure the datacontext of the ListView is the Window, so just like in the Directly set example, you want to give your ListView a name and then add the following to your constructor of the window:

this.MyListView.DataContext = this;
  • Related