You must Sign In to post a response.
  • Category: WPF

    Not getting result without giving DataContext

    Hi Everyone,

    Why student name is not displayed while executing the code untill I give this.DataContext = objstudent;

    anyhow I am bindingstudentname here in xaml right.Please help me out.

    xaml part:
    <RowDefinition Height="*"> </RowDefinition>
    <TextBox Name="TextBox1" Text="{Binding Path=StudentName}"></TextBox>

    Code behind:

    public MainWindow()
    Student objstudent = new Student();
    objstudent.StudentName = "sharmi";


    public class Student
    private string studentname;

    public string StudentName
    return studentname;
    studentname = value;

  • #768797
    Hai Sharmila,
    Actually when you write the code like:

    <TextBox Name="TextBox1" Text="{Binding Path=StudentName}">

    It means you are binding TextBox1.DataContext.StudentName and not TextBox1.StudentName.
    So that is the reason, you need to use

    this.DataContext = objstudent;

    Hope it will be helpful to you.

    Pawan Awasthi(DNS MVM)
    +91 8123489140 (whatsApp), +60 14365 1476(Malaysia)

  • #768809

    As per your design you are binding the local variable to the textbox

    <TextBox Name="TextBox1" Text="{Binding Path=StudentName}">

    so assignment is required for the same. without assign the local variable it shows empty string only.

    Hope this helps you...

    Give respect to your work, Instead of trying to impress your boss.

    Blog :

  • #768816
    Hi Pawan,

    Thank you for your information.But I want to setting my datacontext in xaml iteself.Not in code behind.How can I do that?

    Shouldn't I use like this,If not so please tell me how to define in xaml itself.Sorry I am new to WPF.

    <Grid DataContext="{Binding Student}">
    <TextBox Name="txtname1" Grid.Row="3" Text="{Binding Path=StudentName}"/>

  • Sign In to post your comments