Binding a property from a class to XAML directly

You can set the DataContext in Xaml like this:

<Window xmlns:da="clr-namespace:WPFTestBinding.DataAccess">
    <Window.DataContext>
        <da:Test/>
    <Window.DataContext>

    <TextBox Text="{Binding TestID}"/>
</Window>

Some points to note:

  • The property TestID you are trying to bind is read-only, as it only has get-accessor. Therefore, Binding should be OneWay only.
  • Assigning the DataContext: You can assign the instance holding your model such MainViewModel with ICollection<BaseViewModel> property (which would be having all the derived instances in the collection) or directly the model itself (as in your case). As I have done in code below.

Code

namespace WPFTestBinding.DataAccess
{
    class Test
    {
        public string TestID { get { return "This is my test"; } }
    }
}

public partial class MainWindow : Window
{    
    public MainWindow()
    {
       InitializeComponent();

       DataAccess.Test testInstance = new Test();
       this.DataContext = testInstance;
    }
}

XAML

<TextBox Text="{Binding Path=TestID, Mode=OneWay}" x:Name="txtTestID" />

For more refer:

  • MSDN - Data Binding Overview
  • MSDN - WPF BindingMode
  • Code Project - DataContext-in-WPF
  • SO - What is DataContext for?
  • SO - Difference between Datacontext and ItemSource

The data context is not set. The DataBinding doesn't know where to take TestID from. Here is correct code behind:

namespace WPFTestBinding.DataAccess
{
    class Test
    {
        public string TestID { get { return "This is my test"; } }
    }
}

public partial class MainWindow : Window
{    
    public MainWindow()
    {
       InitializeComponent();
       DataAccess.Test t = new Test();

       DataContext = t;           
    }
}

Tags:

C#

Wpf

Mvvm