The advantage of binding?

I'm not sure I fully understand the advantage of binding. For example, if I want to bind a string value to a TextBlock, I need to do the following:

  • Create a class that extends INotifyPropertyChanged
  • Add a line to this class (say: MyString)
  • Extend the set method to MyString to call another method (say: OnPropertyChanged)
  • Create an OnPropertyChanged method to raise the PropertyChangedEventHandler event

Then I need to create a new instance of the class, set my TextBlock.DataContext to point to this class, and finally add the XAML bit for the binding.

Can someone explain the advantage of this in a simple setup:

TextBlock.Text = MyString;

Thanks!

+4
source share
3 answers

The advantage is that you can change and display the value in several places without having to update any method to add another TextBlock destination each time the value changes. Any new control displays only a property, the rest is automatic.

Now, if you really just set the value in one place and display it in one control, then you are right, there are not many.

+1
source
  • Any changes to MyString will not automatically be reflected in your user interface.
  • Your code will be overwhelmed "when this event happens, update this data", so you will write your own messy data binding logic for each view.
+5
source

The increased use of data binding is not particularly noticeable for binding a TextBlock to a static string.

However, if the value of MyString changes during application execution, it becomes much more useful - especially when the object to which this property belongs does not know the TextBlock. This separation between the user interface and the underlying data layer can be created using a design pattern such as MVVM.

Data binding is also useful for more complex properties, such as items in a ListBox control. Just bind ListBox.Items to a property of type ObservableCollection, and the user interface will automatically update whenever the contents of this collection change.

0
source

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


All Articles