Can't get WPF ListView to bind to ObservableCollection Can't get WPF ListView to bind to ObservableCollection wpf wpf

Can't get WPF ListView to bind to ObservableCollection


Uh, you're trying to do something simple with some terrible magic ;)Your binding should look like {Binding Path=Code}. To make this work you should also set DataContext to this, just like you wrote. This should give you simplest binding. Magic with finding ancestors is not necessary in here.

In advanced applications you should rather use Model - View - ViewModel pattern and set data context to ViewModel object rather than to this, but just for testing and trying WPF out, this approach should be ok.

Here is some sample:

<Window x:Class="binding_test.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>    <ListView ItemsSource="{Binding Path=Code}" /></Grid>

And code behind:

using System.Collections.ObjectModel;using System.Windows;namespace binding_test{    public partial class MainWindow : Window    {        public ObservableCollection<int> Code { get; set; }        public MainWindow()        {            InitializeComponent();            Code = new ObservableCollection<int>();            Code.Add(1);            this.DataContext = this;        }    }}

And here is how you should create listview for your sample. You have special class and you probably don't want to display ToString() result on each object. To display element any way you could imagine, you should use data template and there create controls and bind them to properties of element, that was in list you've bind ListView.

    <ListView ItemsSource="{Binding Code}">        <ListView.ItemTemplate>            <DataTemplate>                <TextBlock Text="{Binding Line}" />            </DataTemplate>        </ListView.ItemTemplate>    </ListView>