WPF Simple Object Binding INotifyPropertyChanged

I created the simplest binding. A text field bound to an object in code.

Event - the text field remains empty.

The DataContext window is set and the binding path exists.

Can you say what's wrong?

Xaml

<Window x:Class="Anecdotes.SimpleBinding" x:Name="MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="SimpleBinding" Height="300" Width="300" DataContext="MainWindow"> <Grid> <TextBox Text="{Binding Path=BookName, ElementName=TheBook}" /> </Grid> </Window> 

Code for

  public partial class SimpleBinding : Window { public Book TheBook; public SimpleBinding() { TheBook = new Book() { BookName = "The Mythical Man Month" }; InitializeComponent(); } } 

Book object

 public class Book : INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged; protected void OnPropertyChanged(string name) { if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs(name)); } } private string bookName; public string BookName { get { return bookName; } set { if (bookName != value) { bookName = value; OnPropertyChanged("BookName"); } } } } 
+6
source share
1 answer

First of all, remove DataContext="MainWindow" , since this sets the DataContext from Window to the string MainWindow, then you specify the ElementName for your binding, which defines the binding source as another control with x:Name="TheBook" , which does not exist in your Window . You can make your code work by removing ElementName=TheBook from your binding and either assigning the DataContext , which is the default source, if none are specified, from Window to TheBook

 public SimpleBinding() { ... this.DataContext = TheBook; } 

or by specifying the RelativeSource your Window binding, which TheBook provides:

 <TextBox Text="{Binding RelativeSource={RelativeSource AncestorType={x:Type Window}}, Path=TheBook.BookName}"/> 

but since you cannot snap to fields, you need to convert TheBook into a property:

 public partial class SimpleBinding : Window { public Book TheBook { get; set; } ... } 
+4
source

Source: https://habr.com/ru/post/950706/


All Articles