Reputation: 45
I have a problem when I try to bind a collection of type observable to listView. I am sure that the collection is updating correctly but nothing happening in the list view.
I am retrieving JSON objects and convert them to a collection of Observable.
public partial class MainWindow : Window
{
public ObservableCollection<post> mproducts = new ObservableCollection<post>();
public MainWindow()
{
InitializeComponent();
DataContext = mproducts;
}
private static readonly HttpClient Client = new HttpClient();
async void OnLoad(object sender, RoutedEventArgs e)
{
HttpResponseMessage response = await Client.GetAsync("https://jsonplaceholder.typicode.com/posts");
response.EnsureSuccessStatusCode();
string data = await response.Content.ReadAsStringAsync();
mproducts = JsonConvert.DeserializeObject<ObservableCollection<post>>(data);
MessageBox.Show(mproducts.Count.ToString());
}
public class post
{
public string UserId { get; set; }
public string Id { get; set; }
public string Title { get; set; }
public string Body { get; set; }
}
}
this is the XAML class:
<Window x:Class="WpfApp1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfApp1"
mc:Ignorable="d"
Loaded="OnLoad"
Title="MainWindow" Height="450" Width="800">
<Grid>
<ListView x:Name="products" Margin="400,0,0,0" Width="600" SelectionChanged="ListView_SelectionChanged" ItemsSource="{Binding mproducts}"; >
<ListView.View>
<GridView>
<GridViewColumn Width="160" Header="Description" DisplayMemberBinding="{Binding UserId}"/>
<GridViewColumn Width="160" Header="Date Filed" DisplayMemberBinding="{Binding Id}"/>
<GridViewColumn Width="160" Header="Filed By" DisplayMemberBinding="{Binding Title}"/>
<GridViewColumn Width="150" Header="Page" DisplayMemberBinding="{Binding Body}"/>
<GridViewColumn Width="Auto" Header="" />
</GridView>
</ListView.View>
</ListView>
</Grid>
</Window>
when the app loads it shows in the Message box number 100, which means the collection is updated.
Upvotes: 0
Views: 1011
Reputation: 1031
The binding of the ListBox
should look like this
ItemsSource="{Binding}"
because you are binding to the collection itself which is stored in the DataContext
. Also in your code you should do DataContext = mproducts;
in the OnLoad
event after you assign the collection to mproducts
like this:
mproducts = JsonConvert.DeserializeObject<ObservableCollection<post>>(data);
DataContext = mproducts;
Upvotes: 1