How to use DataContext?


What I am trying to do is simply have a combobox populate with data from an sqlite table. While I have done this with code methods, I wold really like to do this in what I can see is the better WPF way to do things.

From what I understand the flow should go something like this:

I should have a class that holds the data, I made a quick class which the default constructor is to connect to the database and dump it's results to a list like so:

internal class mainmenusql { private List<string> _Jobs; public mainmenusql() { SQLiteConnection conn = new SQLiteConnection(); conn.ConnectionString = "Data Source=C:\\Users\\user\\Documents\\db.sqlite;Version=3"; try { conn.Open(); SQLiteDataReader reader; SQLiteCommand command = new SQLiteCommand(conn); command.CommandType = CommandType.Text; command.CommandText = "SELECT * FROM Tasks"; reader = command.ExecuteReader(); if (reader.HasRows) { while (reader.Read()) { _Jobs.Add(reader.GetValue(0).ToString()); } } else { MessageBox.Show("No records"); } } catch (Exception err) { MessageBox.Show(err.Message); } finally { conn.Close(); } } }

Having some errors with the list "Object reference not set to an instance of an object".

But anyways, the next step should be to set the DataContext of the form to this object right?

public MainWindow() { DataContext = new mainmenusql(); InitializeComponent(); }

And finally the combobox should have a binding right?

<Window x:Class="sqliteDatacontext.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> <ComboBox DataContext="{Binding Path=_Jobs}" HorizontalAlignment="Left" Margin="141,124,0,0" VerticalAlignment="Top" Width="120"/> </Grid> </Window>

What am I doing wrong here?


For binding to something of a datacontext, it needs to be exposed via public getter / setter...

public class mainmenusql { public List<string> _Jobs { get ; protected set; } public mainmenusql() { _Jobs = new List<string>(); // rest of populating your data } }

The binding in your window control is the ItemsSource

<ComboBox ItemsSource="{Binding Path=_Jobs}" />

The "DataContext" is applied to the entire window... From that being the basis, any of your controls can have their element "bound" to almost anything "publicly" available ON your data context... in this case, a ComboBox list of choices comes from its "ItemSource" property... So you want the ITEMSOURCE pointing to your _Jobs.


  • PHP MySQL Connection error - Implementing Retry logic
  • multiple update statements throw “cannot open”
  • SQLite: Column 'date' does not belong to table
  • sqlite database is locked exception
  • Image.MemoryStream : Parameter not valid
  • How to add parameters to a Sqllitecommand
  • How to personalize a timeline with R?
  • Unable to get Emma Coverage for Android [duplicate]
  • How do I manage org and space users in bluemix using cf command line?
  • Installing a python package in a desired folder
  • ImportError: cannot import name COMError in python
  • Delphi. Analog of Memo/RichEdit
  • Where in the relevant specification is it documented that some comments in a SQL script are, in fact
  • Where to save the local DB created for iphone app?
  • Is it possible to create a self-extracting archive which will run a specific file when unzipped?
  • Reading XML into Datatable gives incorrect DateTime when the time has Time Zone info
  • Iterate twice through a DataReader
  • Python to parent/child JSON
  • 'doc_del_count' bigger than 'doc_count' on CouchDB
  • c# winform DrawToBitmap offscreen
  • Changing Jupyter Notebook start up folder by modifying “start in” not working any more
  • Open Existing DB in MySQL WorkBench
  • Ajax Upload File: $_FILES is empty but files exists in request header
  • How can I extract results of aggregate queries in slick?
  • Needing to do .toArray() to get output of mongodb .find() on key name not value
  • Bad request using file_get_contents for PUT request in PHP
  • MongoDB in PHP using aggregate to group by _id is null not working
  • How do I fake an specific browser client when using Java's Net library?
  • How to redirect a user to a different server and include HTTP basic authentication credentials?
  • SSO with signing and signature validation doesn't work
  • Deserializing XML into class C#
  • Can I make an Android app that runs a web view in Chrome 39?
  • Apache 2.4 - remove | delete | uninstall
  • Run Powershell script from inside other Powershell script with dynamic redirection to file
  • How to include full .NET prerequisite for Wix Burn installer
  • Turn off referential integrity in Derby? is it possible?
  • LevelDB C iterator
  • Linking SubReports Without LinkChild/LinkMaster
  • costura.fody for a dll that references another dll
  • jQuery Masonry / Isotope and fluid images: Momentary overlap on window resize