Shaul Zuarets
Shaul Zuarets

Reputation: 849

text box value won't updated using data bind

In order to prevent long discussion in the comment section I'm asking it again.

I have a TextBox which is bound to an object.

When I'm changing the object value, the TextBox text value won't change.

I read all most each discussion exist here about this and didn't figure it out.

XAML:

<TabItem Header="תלמידים" Name="Tabstudents" >
            <Grid Height="757" Margin="0">
                <Border BorderBrush="Silver" BorderThickness="1" Height="450" HorizontalAlignment="Stretch" Margin="4,0,11,287" Name="brdrStudents" VerticalAlignment="Bottom" Width="Auto">
                    <Grid Height="441">
                        <TextBlock Style="{StaticResource textStyle}" Height="33" Name="txtblkStudenName" Text="שם פרטי:" Width="159" HorizontalAlignment="Left" VerticalAlignment="Bottom" Margin="20,0,0,400" />
                        <TextBlock Style="{StaticResource textStyle}" Height="33" Name="txtblkStudenNotes" Text="שם משפחה:" Width="159" HorizontalAlignment="Left" VerticalAlignment="Bottom" Margin="20,00,0,360" />
                        <TextBlock Style="{StaticResource textStyle}" Height="33" Name="txtBlkStudenTecher" Text="תעודת זהות:" Width="159" HorizontalAlignment="Left" VerticalAlignment="Bottom" Margin="20,0,0,320" />
                        <TextBlock Style="{StaticResource textStyle}" Height="33" Name="txtblkStudenAdress" Text="כתובת:" Width="159" HorizontalAlignment="Left" VerticalAlignment="Bottom" Margin="20,0,0,120" />
                        <TextBlock Style="{StaticResource textStyle}" Height="33" Name="txtBlkStudenPrice" Text="טלפון בית:" Width="159" HorizontalAlignment="Left" VerticalAlignment="Bottom" Margin="20,0,0,280" />
                        <TextBlock Style="{StaticResource textStyle}" Height="33" Name="txtblkStudenPicForm" Text="אישור צילום:" Width="159" HorizontalAlignment="Left" VerticalAlignment="Bottom" Margin="460,0,0,400" />
                        <TextBlock Style="{StaticResource textStyle}" Height="33" Name="txtBlkStudenDates" Text="טלפון סלולרי:" Width="159" HorizontalAlignment="Left" VerticalAlignment="Bottom" Margin="20,0,0,240" />
                        <TextBlock Style="{StaticResource textStyle}" Height="33" Name="txtblkStudenMedical" Text="בעיות רפואיות:" Width="159" HorizontalAlignment="Left" VerticalAlignment="Bottom" Margin="460,0,0,320" />
                        <TextBlock Style="{StaticResource textStyle}" Height="33" Name="txtBlkStudenDivideMoney" Text="טלפון הורים:" Width="159" HorizontalAlignment="Left" VerticalAlignment="Bottom" Margin="20,0,0,200" />
                        <TextBlock Style="{StaticResource textStyle}" Height="33" Name="txtblkStudenParentsConf" Text="אישור הורים:" Width="159" HorizontalAlignment="Left" VerticalAlignment="Bottom" Margin="460,0,0,360" />
                        <TextBlock Style="{StaticResource textStyle}" Height="33" Name="txtBlkStudenPlace" Text="שמות ההורים:" Width="159" HorizontalAlignment="Left" VerticalAlignment="Bottom" Margin="20,0,0,160" />
                        <TextBlock Style="{StaticResource textStyle}" Height="33" Name="txtblkStudenBirth" Text="תאריך לידה:" Width="159" HorizontalAlignment="Left" VerticalAlignment="Bottom" Margin="20,0,0,80" />
                        <TextBlock Style="{StaticResource textStyle}" Height="33" Name="txtblkStudenClasses" Text="רשימת חוגים:" Width="159" HorizontalAlignment="Left" VerticalAlignment="Bottom" Margin="663,0,0,280" />
                        <TextBlock Height="33" HorizontalAlignment="Left" Margin="1006,0,0,400" Name="txtBlkPayments" Style="{StaticResource textStyle}" Text="תשלומים:" VerticalAlignment="Bottom" Width="159" />

                        <TextBox Height="36" HorizontalAlignment="Left" Margin="174,0,0,400" Name="txtStudenName" VerticalAlignment="Bottom" Width="240" IsEnabled="False" >
                            <TextBox.Text>
                                <Binding NotifyOnSourceUpdated="True" Path="firstName" UpdateSourceTrigger="PropertyChanged" >
                                </Binding>
                            </TextBox.Text>
                        </TextBox>
                        <TextBox Height="36" HorizontalAlignment="Left" Margin="174,0,0,360" Name="txtStudenLastName" VerticalAlignment="Bottom" Width="240" IsEnabled="False" >
                            <TextBox.Text>
                                <Binding NotifyOnSourceUpdated="True" Path="lastName" UpdateSourceTrigger="PropertyChanged" >
                                </Binding>
                            </TextBox.Text>
                        </TextBox>
                        <TextBox Height="36" HorizontalAlignment="Left" Margin="174,0,0,320" Name="txtStudenID" VerticalAlignment="Bottom" Width="240" IsEnabled="False" >
                            <TextBox.Text>
                                <Binding NotifyOnSourceUpdated="True" Path="studentID" UpdateSourceTrigger="PropertyChanged" >
                                </Binding>
                            </TextBox.Text>
                        </TextBox>
                        <TextBox Height="36" HorizontalAlignment="Left" Margin="174,0,0,120" Name="txtStudenAdress" VerticalAlignment="Bottom" Width="240" IsEnabled="False" Text="{Binding lastName}"/>
                        <TextBox Height="36" HorizontalAlignment="Left" Margin="174,0,0,280" Name="txtStudenHomePhone" VerticalAlignment="Bottom" Width="240" IsEnabled="False" Text="{Binding homePhone}"/>
                        <TextBox Height="36" HorizontalAlignment="Left" Margin="174,0,0,240" Name="txtStudenCellPhone" VerticalAlignment="Bottom" Width="240" IsEnabled="False" Text="{Binding cellPhone}"/>
                        <TextBox Height="36" HorizontalAlignment="Left" Margin="614,0,0,320" Name="txtStudenMedical" VerticalAlignment="Bottom" Width="240" IsEnabled="False" Text="{Binding medProblems}"/>
                        <TextBox Height="36" HorizontalAlignment="Left" Margin="174,0,0,200" Name="txtStudenParentsPhone" VerticalAlignment="Bottom" Width="240" IsEnabled="False" Text="{Binding parentsPhone}"/>
                        <TextBox Height="36" HorizontalAlignment="Left" Margin="174,0,0,160" Name="txtStudenParentsName" VerticalAlignment="Bottom" Width="240" IsEnabled="False" Text="{Binding parentsName}"/>
                        <TextBox Height="36" HorizontalAlignment="Left" Margin="174,0,0,80" Name="txtStudenBirthDay" VerticalAlignment="Bottom" Width="240" IsEnabled="False" Text="{Binding birthDate}"/>

                        <Button Content="ערוך תלמיד" Style="{StaticResource myButtonStyle}" Height="40" HorizontalAlignment="Left" Margin="130,0,0,10" Name="btnEditStuden" VerticalAlignment="Bottom" Width="118" />
                        <Button Content="הוסף תלמיד" Style="{StaticResource myButtonStyle}" Height="40" HorizontalAlignment="Left" Margin="6,0,0,10" Name="btnAddStuden" VerticalAlignment="Bottom" Width="118" />
                        <Button Content="מחק תלמיד" Style="{StaticResource myButtonStyle}" Height="40" HorizontalAlignment="Left" Margin="254,0,0,10" Name="btnDeleteStudent" VerticalAlignment="Bottom" Width="118" />
                        <Button Style="{StaticResource myButtonStyle}" Content="הבא" Height="23" HorizontalAlignment="Left" Margin="633,0,0,6" Name="btnStudenNext" VerticalAlignment="Bottom" Width="75"/>
                        <Button Style="{StaticResource myButtonStyle}" Content="הקודם" Height="23" HorizontalAlignment="Left" Margin="552,0,0,6" Name="btnStudenPrev" VerticalAlignment="Bottom" Width="75"/>

                        <ListBox Height="207" HorizontalAlignment="Left" Margin="614,0,0,80" Name="lstBxClasses" VerticalAlignment="Bottom" Width="240" ItemsSource="{Binding Path=classesList.className}"/>


                        <TextBlock Height="33" HorizontalAlignment="Left" Margin="913,0,0,260" Name="txtBlkDebt" Style="{StaticResource textStyle}" Text="יתרת חשבון:" VerticalAlignment="Bottom" Width="131" />

                        <Rectangle Height="4" HorizontalAlignment="Left" Margin="913,0,0,400" Name="rectangle2" Stroke="Black" VerticalAlignment="Bottom" Width="312" />
                        <Rectangle Height="426" HorizontalAlignment="Left" Margin="900,0,0,10" Name="rectangle3" Stroke="Black" VerticalAlignment="Bottom" Width="333" />
                        <TextBox Height="36" HorizontalAlignment="Left" IsEnabled="False" Margin="909,0,0,226" Name="txtDebt" VerticalAlignment="Bottom" Width="312" />
                        <Button Content="הרשם לחוג" Height="40" HorizontalAlignment="Left" Margin="909,0,0,20" Name="btnPay" Style="{StaticResource myButtonStyle}" VerticalAlignment="Bottom" Width="312" Click="btnPay_Click" />
                        <CheckBox Height="36" HorizontalAlignment="Left" Margin="614,15,0,0" Name="cbPicConf" VerticalAlignment="Top" FontSize="24" Width="38" BorderThickness="1" IsChecked="{Binding isPicFormExists}" IsEnabled="False" />
                        <CheckBox BorderThickness="1" FontSize="24" Height="36" HorizontalAlignment="Left" Margin="614,51,0,0" Name="cbParentsConf" VerticalAlignment="Top" Width="38" IsChecked="{Binding isParentsConfExists}" IsEnabled="False" />

                    </Grid>
                </Border>
                <Label Content="רשימת תלמידים" HorizontalAlignment="Stretch" Margin="18,0,30,234" Name="lblStudentsList" VerticalAlignment="Bottom" Width="1208" VerticalContentAlignment="Center" HorizontalContentAlignment="Center" FontSize="36" />
                <TextBlock Height="33" HorizontalAlignment="Left" Margin="68,0,0,196" Name="textBlock1" Style="{StaticResource textStyle}" Text="שם פרטי:" VerticalAlignment="Bottom" Width="159" />
                <TextBlock Height="33" HorizontalAlignment="Left" Margin="492,0,0,192" Name="textBlock2" Style="{StaticResource textStyle}" Text="תעודת זהות:" VerticalAlignment="Bottom" Width="159" />
                <TextBox Height="36" HorizontalAlignment="Left" IsEnabled="True" Margin="219,0,0,192" Name="txtFindFirstName" VerticalAlignment="Bottom" Width="240" />
                <TextBox Height="36" HorizontalAlignment="Left" IsEnabled="True" Margin="638,0,0,192" Name="txtFindID" VerticalAlignment="Bottom" Width="240" />
                <DataGrid AutoGenerateColumns="False" Height="126" Name="dgStudents" Width="1157" Margin="25,0,74,64" VerticalAlignment="Bottom" ItemsSource="{Binding}" ScrollViewer.CanContentScroll="True" 
  ScrollViewer.VerticalScrollBarVisibility="Auto"
  ScrollViewer.HorizontalScrollBarVisibility="Auto" IsReadOnly="True" SelectionChanged="dgStudents_SelectionChanged">
                    <DataGrid.Columns>
                        <DataGridTextColumn Header="שם פרטי" Width="175" Binding="{Binding firstName}" />
                        <DataGridTextColumn Header="שם משפחה" Width="175" Binding="{Binding lastName}" />
                        <DataGridTextColumn Header="תעודת זהות" Width="175" Binding="{Binding studentID}" />
                        <DataGridTextColumn Header="תאריך לידה" Width="175" Binding="{Binding birthDate}" />
                        <DataGridTextColumn Header="מאזן חשבון" Width="175" Binding="{Binding accountBalance}" />
                        <DataGridTextColumn Header="טלפון - בית" Width="175" Binding="{Binding homePhone}" />
                        <DataGridTextColumn Header="טלפון סלולרי" Width="175" Binding="{Binding cellPhone}" />
                        <DataGridTextColumn Header="טלפון - הורים" Width="175" Binding="{Binding parentsPhone}" />
                        <DataGridTextColumn Header="שם ההורים" Width="175" Binding="{Binding parentsName}" />
                        <DataGridTextColumn Header="כתובת" Width="175" Binding="{Binding adress}" />
                        <DataGridCheckBoxColumn Header="טופס אישור צילום" Width="175" Binding="{Binding isPicFormExists}" />
                        <DataGridCheckBoxColumn Header="טופס אישור הורים" Width="175" Binding="{Binding isParentsConfExists}" />
                        <DataGridTextColumn Header="בעיות רפואיות" Width="175" Binding="{Binding medProblems}" />
                    </DataGrid.Columns>
                </DataGrid>
            </Grid>
        </TabItem>

Codebehind:

 public partial class MainWindow : Window, INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;
    private student _selectedStudent;

    public student selectedStudent  // This is the object
    {
        get { return _selectedStudent; }
        set
        {
            if (value != _selectedStudent)
            {
                _selectedStudent = value;
                OnPropertyChanged("_selectedStudent");
            }
        }
    }
    public MainWindow()
    {
            InitializeComponent();

            selectedStudent = clsLoadStudent();
            this.DataContext = selectedStudent;  // Here I use the object as a datacontext.
    }
    private void dgStudents_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        selectedStudent = new student();
        selectedStudent = (student)dgStudents.SelectedItem;


    }
    protected void OnPropertyChanged(string propertyName)
    {
        if (PropertyChanged != null) // if there is any subscribers
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }
}

I have been told to implement OnPropertyChanged. I did, I think.

Upvotes: 0

Views: 1117

Answers (3)

user007
user007

Reputation: 1192

You need to set DataContext again:

private void dgStudents_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        selectedStudent = new student();
        DataContext = (student)dgStudents.SelectedItem;
    }

Upvotes: 0

S2S2
S2S2

Reputation: 8502

You have implemented the INotifyPropertyChanged on MainWindow class which is correct, but you are using the DataContext as the property name as your code suggests (which would not work and could be the reason your binding is not working):

//Below DataContext binding needs to be changed, you are binding directly to property, instead you should bind to you MainWindow object
public MainWindow()
{
        InitializeComponent();

        selectedStudent = clsLoadStudent();
        //this.DataContext = selectedStudent;  // Does not work
        this.DataContext = this;  // Correct way           
}   

Then, you should change Textbox Text property binding to point to properties in your student object property as below (selectedStudent.FirstName):

<TextBox Height="36" HorizontalAlignment="Left" Margin="174,0,0,400" Name="txtStudenName" VerticalAlignment="Bottom" Width="240" IsEnabled="False" Text={Binding selectedStudent.FirstName, NotifyOnTargetUpdated=True, UpdateSourceTrigger=PropertyChanged}/>

Also, you should raise the propertychanged event for the property name:

OnPropertyChanged("selectedStudent");

Upvotes: 1

Sheridan
Sheridan

Reputation: 69987

If you are going to use the MainWindow.xaml.cs, then I would recommend that you define a DependencyProperty to bind to instead:

public static readonly DependencyProperty StudentProperty = DependencyProperty.
    Register("Student", typeof(Student), typeof(MainWindow), new 
    UIPropertyMetadata(100.0));

public Student Student
{
    get { return (Student)GetValue(StudentProperty); }
    set { SetValue(StudentProperty, value); }
}

Then, you must set your DataContext... the easiest (but not best) way is to do this in the constructor:

public MainWindow()
{
    InitializeComponent();
    Student = new Student() { FirstName = "John", OtherProperty = "Something else" };
    DataContext = this;
}

Now bind to a property from your Student object (assuming you have a property in there named FirstName):

<TextBox Text="{Binding Student.FirstName}" />

Upvotes: 0

Related Questions