Reputation: 1057
So I have a VERY simple UI design with a ListView and a button. I want to populate the listview when clicking the button.
<Grid>
<Button Click="ButtonBase_OnClick" Content="Button" HorizontalAlignment="Left" Margin="349,259,0,0" VerticalAlignment="Top" Width="75"/>
<ListView Margin="10,10,10,202" Name="lvUsers" ItemsSource="{Binding SomeData.Users}">
<ListView.View>
<GridView>
<GridViewColumn Header="Name" Width="120" DisplayMemberBinding="{Binding Name}" />
</GridView>
</ListView.View>
</ListView>
</Grid>
I have bound the ItemSource property of the ListView to be SomeData.Users
which is an ObservableCollectiuon which should notify the UI when it's updated, added, removed or refreshed. And then down below where I have the column I am binding the DisplayMember to the Name
property of the observable collection.
Here is the SomeData
class
public class SomeData
{
public static ObservableCollection<User> Users { get; } = new ObservableCollection<User>();
public static void Populate()
{
Users.Add(new User() { Name = "John Doe", Age = 42, Mail = "[email protected]" });
Users.Add(new User() { Name = "Jane Doe", Age = 39, Mail = "[email protected]" });
Users.Add(new User() { Name = "Sammy Doe", Age = 7, Mail = "[email protected]" });
}
}
public class User
{
public string Name { get; set; }
public int Age { get; set; }
public string Mail { get; set; }
}
And here is the MainWindow.cs
public MainWindow()
{
InitializeComponent();
}
private void ButtonBase_OnClick(object sender, RoutedEventArgs e)
{
SomeData.Populate();
}
afaik I shouldnt have to set the DataContext anywhere.. Right?
Upvotes: 3
Views: 2336
Reputation: 2767
The problem is that your Binding syntax is wrong. You are trying to bind to an static property, try this:
"{Binding Source={x:Static YourNameSpace:SomeData.Users}}"
Or if you are using WPF 4.5 or newer:
"{Binding Path=(YourNameSpace:SomeData.Users)}"
One tip: with problems like yours always try to take a look to your output window and look for System.Window.Data Error
, these are commonly binding exceptions that occur when a binding expression can not be resolved. In your case I am sure you will find this exception.
Upvotes: 5
Reputation: 859
You have to set the DataContext for the xaml.
Add datacontext to mainwindow
public MainWindow()
{
InitializeComponent();
this.DataContext = new SomeData();
}
and change the xaml ItemsSource binding to
ItemsSource="{Binding Users}"
Upvotes: 2