Junior — Middle
Can you explain how data binding is implemented in WPF and how it interacts with the interface?
sobes.tech AI
Answer from AI
In WPF, the data binding system allows automatic linking of interface element properties with data in code (for example, with model or view objects). This is achieved through a mechanism that tracks changes in the data source and updates the UI, and vice versa — when the UI changes, data can be updated.
Main components of binding:
- Data source — an object containing data (e.g., ViewModel).
- Binding target — a property of a UI element (e.g., TextBox.Text).
- Binding — an object describing the connection between the source and the target.
For proper data update operation, the source must implement the INotifyPropertyChanged interface, which notifies the UI of changes.
Example:
public class Person : INotifyPropertyChanged
{
private string name;
public string Name
{
get => name;
set
{
if (name != value)
{
name = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(Name)));
}
}
}
public event PropertyChangedEventHandler PropertyChanged;
}
In XAML, you can bind a TextBox to this property:
<TextBox Text="{Binding Name, UpdateSourceTrigger=PropertyChanged}" />
And set the DataContext in code:
this.DataContext = new Person();
Thus, when the Name property in the Person object changes, the interface automatically updates, and vice versa.