Search

Thursday, July 30, 2015
0 comments

How to bind a TextBox to an instance of a custom class object in WPF

11:39 PMThursday, July 30, 2015
If you want to bind the text box with the instance of customer class object also call one way binding in wpf. first to add a cs class in the project. In which you should take one or more public properties , i will take two public properties and one static method. That static method will return class object.  Now, your code look like:


1. Add a Class in the project also paste the below mentioned code. But remember that your class name is match with csharp file name; namespace name match with code.
  
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SplashSCreen
{
   public class Student
    {
        public string Name { get; set; }
        public string Email { get; set; }
        public static Student GetRecord()
        {
            var student = new Student();
            {
                student.Name = "Jacob";
                student.Email = "narenkumar851@gmail.com";
            };
            return student;
        }
    }
}

2. Add a new window in the project.
3. Paste this code inside the grid of window class.

 <Grid>
        <TextBox x:Name="textBox" HorizontalAlignment="Left" Height="23" Margin="49,45,0,0" TextWrapping="Wrap" Text="{Binding Path=Name}" VerticalAlignment="Top" Width="120"/>

        <TextBlock x:Name="textBlock" HorizontalAlignment="Left" Margin="49,21,0,0" TextWrapping="Wrap" Text="Name:" VerticalAlignment="Top"/>

        <TextBlock x:Name="textBlock_Copy" HorizontalAlignment="Left" Margin="52,73,0,0" TextWrapping="Wrap" Text="Email:" VerticalAlignment="Top"/>

        <TextBox x:Name="textBox_Copy" HorizontalAlignment="Left" Height="23" Margin="49,107,0,0" TextWrapping="Wrap" Text="{Binding Path=Email}" VerticalAlignment="Top" Width="120"/>


    </Grid>

4. Add the business logic code in csharp file 

namespace SplashSCreen
{
    /// <summary>
    /// Interaction logic for bindtext.xaml
    /// </summary>
    public partial class bindtext : Window
    {
        public bindtext()
        {
            InitializeComponent();

            DataContext = Student.GetRecord();
         

        }

     
    }
}

Now , code generate the following output

How to bind a TextBox to an instance of a custom class object in WPF
Protected by Copyscape Online Copyright Protection Software

0 comments :

Post a Comment

 
Toggle Footer
Top