How can I bind a List as ItemSource to ListView in XAML?
- by Jonas
I'm learning WPF and would like to have a collection similar to a LinkedList, to where I can add and remove strings. And I want to have a ListView that listen to that collection with databinding. How can I do bind a simple list collection to a ListView in XAML?
My idea (not working) is something like this:
<Window x:Class="TestApp.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<LinkedList x:Key="myList"></LinkedList> //Wrong
<Window.Resources>
<Grid>
<ListView Height="100" HorizontalAlignment="Left" Margin="88,134,0,0"
Name="listView1" VerticalAlignment="Top" Width="120"
ItemsSource="{Binding Source={StaticResource myList}}"/> //Wrong
</Grid>
</Window>
All my code (updated version, not working):
<Window x:Class="TestApp.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<TextBox Height="23" HorizontalAlignment="Left" Margin="12,12,0,0"
Name="textBox1" VerticalAlignment="Top" Width="120" />
<Button Content="Button" Height="23" HorizontalAlignment="Right"
Margin="0,12,290,0" Name="button1" VerticalAlignment="Top" Width="75"
Click="button1_Click" />
<ListView Height="100" HorizontalAlignment="Left" Margin="88,134,0,0"
Name="listView1" VerticalAlignment="Top" Width="120"
ItemsSource="{Binding myList}"/>
</Grid>
</Window>
C#-code:
namespace TestApp
{
public partial class MainWindow : Window
{
ObservableCollection<string> myList = new ObservableCollection<string>();
public MainWindow()
{
InitializeComponent();
myList.Add("first string");
}
private void button1_Click(object sender, RoutedEventArgs e)
{
myList.Add(textBox1.Text);
textBox1.Text = myList.Count+"st";
}
}
}