I came from a Linux heavy environment, where I wrote most of my tools in Python but now I am in a windows heavy environment, and need to share my tools with my team and some need to be GUI driven so I am trying to learn C#/WPF. I'm getting confused on Data Binding to an ObservableCollection in the code behind. I can get it work, but I don't understand why, which bothers me.
My code is simple, and I am literally just trying to get the basics working so I can move on to more complicated parts:
XAML:
<ListView x:Name="lvUrlList" HorizontalAlignment="Left" Height="441" Margin="15,62,0,0" VerticalAlignment="Top" Width="486" SelectionChanged="listView_SelectionChanged" ItemsSource="{Binding Path=urlList, ElementName=MainWindow1}">
<ListView.ItemTemplate>
<DataTemplate>
<WrapPanel>
<TextBlock Text="{Binding domain}"/>
</WrapPanel>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
Code Behind:
namespace ReferalScraper
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
//public ObservableCollection<Url> urlList { get; set; } // Method 1
public ObservableCollection<Url> urlList = new ObservableCollection<Url>(); // Method 2
public MainWindow()
{
// urlList = new ObservableCollection<Url>(); // Method 1
InitializeComponent();
urlList.Add(new Url() { domain = "www.test1.com" });
}
public class Url
{
public string domain { get; set; }
}
private void button_Click(object sender, RoutedEventArgs e)
{
urlList.Add(new Url() { domain = "www.test2.com" });
urlList.Add(new Url() { domain = "www.test3.com" });
}
}
}
The uncommented method for creating and instantiating the ObservableCollection doesn't work, the code compiles but I get the output error:
System.Windows.Data Error: 40 : BindingExpression path error: 'urlList' property not found on 'object' ''MainWindow' (Name='MainWindow1')'. BindingExpression:Path=urlList; DataItem='MainWindow' (Name='MainWindow1'); target element is 'ListView' (Name='lvUrlList'); target property is 'ItemsSource' (type 'IEnumerable')
Which I understand that it means it can't find the urlList object in MainWindow. But I don't understand why it can't find it.
If I switch to the Method 1 and uncomment the following two lines (and comment out the "Method 2" part) it works fine:
public ObservableCollection<Url> urlList { get; set; }
...
public MainWindow(){
urlList = new ObservableCollection<Url>()
Why is declaring the ObserverableCollection with the { get; set }
needed? I don't quite grasp why I can't just instantiate my ObservableCollection as an empty ObserverableCollection like I am in Method 2.
I'm feeling incredibly dense, and haven't quite been able to track down the right terminology to even get close to answering my questions. Can anyone explain to a not so bright fellow what I am missing?
I have a feeling this is some C# understanding that I am missing.