Both of these examples are with default value, you will find it in the constructor of model "Hello world!"
XAML datacontext
Add new WPF application project, add new model like:
namespace HelloWorldDataContext { public class HelloWorldDataContextModel { public string HelloWorld { get; set; } public HelloWorldDataContextModel() { HelloWorld = "Hello world!"; } } }
Then XAML:
<Window x:Class="HelloWorldDataContext.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:HelloWorldDataContext" Title="MainWindow" Height="350" Width="525"> <Window.Resources> <local:HelloWorldDataContextModel x:Key="HelloWorldDataContext" /> </Window.Resources> <Grid DataContext="{StaticResource HelloWorldDataContext}"> <TextBox HorizontalAlignment="Left" Height="23" Margin="222,127,0,0" TextWrapping="Wrap" Text="{Binding HelloWorld}" VerticalAlignment="Top" Width="120"/> </Grid> </Window>
Important lines in XAML on which you should take care are:
xmlns:local="clr-namespace:HelloWorldDataContext"
Where name space is declared in model like:
namespace HelloWorldDataContext
<local:HelloWorldDataContextModel x:Key="HelloWorldDataContext" />
<Grid DataContext="{StaticResource HelloWorldDataContext}">
Example project you can download from here.
Programmatically setting datacontext
XAML:
<Window x:Class="ProgramaticallyDataContext.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 HorizontalAlignment="Left" Height="23" Margin="147,78,0,0" TextWrapping="Wrap" Text="{Binding HelloWorld}" VerticalAlignment="Top" Width="120"/> </Grid> </Window>
Test Model is same like in above example, code behind (MainWindow.xaml.cs) is like:
public MainWindow() { InitializeComponent(); HelloWorldDataContextModel objHW = new HelloWorldDataContextModel(); objHW.HelloWorld = "Hello world"; this.DataContext = objHW; }
Example you can download from here.