1
votes

I have a Textbox in WPF which has its "Text" Property bound to a string "EmployeeSource.ID" with Mode=TwoWay. My problem is that when i change the EmployeeSource object, the binding does not work. What is wrong in my approach?

XAML

<TextBox x:Name="NameTextBox" Margin="5,5,10,5" TextWrapping="Wrap"
Text="{Binding SelectedEmployee.Name, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
Grid.Row="1" Grid.Column="1" />

Code Behind

private Employee _selectedEmployee;

public Employee SelectedEmployee
{
    get { return _selectedEmployee; }
    set
    {
        _selectedEmployee = value;
        UpdateTextBoxes();
    }
}

private void UpdateTextBoxes()
{
    NameTextBox.Text = SelectedEmployee?.Name;
}
1
Your object/property does not implement the INotifyPropertyChanged interface. It needs to be implemented to work with binding. See: stackoverflow.com/questions/8186864/… - pKami

1 Answers

0
votes

Please try the code below. You need to implement the INotifyPropertyChanged interface inorder to achieve data binding in WPF. This is the basic concept of WPF data binding and MVVM pattern. This should work for you.

Code behind:

public class YourClassName : INotifyPropertyChanged
{
    // These fields hold the values for the public properties.
    private Employee _selectedEmployee;

    public event PropertyChangedEventHandler PropertyChanged;

    private void NotifyPropertyChanged(String info)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(info));
        }
    }

    // The constructor is private to enforce the factory pattern.
    private YourClassName()
    {
        _selectedEmployee = new Employee();
    }

    public Employee selectedEmployee
    {
        get
        {
            return this._selectedEmployee;
        }
        set
        {
            if (value != this._selectedEmployee)
            {
                this._selectedEmployee = value;
                NotifyPropertyChanged("selectedEmployee");
            }
        }
    }
}

XAML :

<TextBox x:Name="NameTextBox" Margin="5,5,10,5" TextWrapping="Wrap"
Text="{Binding selectedEmployee.Name, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
Grid.Row="1" Grid.Column="1" />