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:
    <Grid>
    <Grid.RowDefinitions>
    <RowDefinition Height="*"> </RowDefinition>
    </Grid.RowDefinitions>
    <TextBox Name="TextBox1" Text="{Binding Path=StudentName}"></TextBox>
    </Grid>

    Code behind:

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

    }

    public class Student
    {
    private string studentname;

    public string StudentName
    {
    get
    {
    return studentname;
    }
    set
    {
    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.

    Regards,
    Pawan Awasthi(DNS MVM)
    +91 8123489140 (whatsApp), +60 14365 1476(Malaysia)
    pawansoftit@gmail.com

  • #768809
    Hi,

    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.

    N@veen
    Blog : http://naveens-dotnet.blogspot.in/

  • #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}"/>
    </Grid>


  • Sign In to post your comments