Binding a TextBlock to a field in Local Database in Wp7

Go To


i'm new to wp7 development. I am trying to bind a Textblock to a local database field using Local Database of isolated Storage.

I use following code....

<TextBlock x:Name="field_name" TextWrapping="Wrap" Text="{Binding fieldName}">

here field name is a database column and data is retrieved using LINQ to SQL into a observable collection.

The datacontext method works for listbox but not with TextBlock alone...

any ideas..? thanks..!

2012-04-03 19:43
by Vikas Raturi


You have to set the DataContext property of the textblock to the object to which it should be bound.

field_name.DataContext = MyObjectFromDatabase
2012-04-03 19:46
by Nico Schertler


Don't do direct binding.

What you want to do is this:


<TextBlock x:Name="field_name" TextWrapping="Wrap" Text="{Binding fieldName}">


public class ViewModel:INotifyPropertyChanged

public ViewModel()
//Load DB and set the fieldName property here
public string FieldName
get{return _fieldName;}

protected void OnPropertyChanged(string propertyName)
        PropertyChanged(this,new PropertyChangedEventArgs(propertyName));
public event public event PropertyChangedEventHandler PropertyChanged;


This is something called MVVM (ModelViewViewModel). The ViewModel gets bound to the DataContext of the view and you can then bind the properties of the ViewModel to elements in the view. There are lots of frameworks around to make this easier:

  1. MVVMLite - on
  2. Caliburn.Micro - on

Which all help you bind the ViewModel to the View and provide a stack of helpers so you write less code. If you're going to do any Xaml-based coding you really need to be coding MVVM as this is the defacto "standard" way to code this type of technology.

2012-04-03 20:06
by Faster Solutions