4

I am not sure that 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:

  1. Create a class that extends INotifyPropertyChanged
  2. Add a string to that class (say: MyString)
  3. Extend the set method for MyString so that it calls another method (say: OnPropertyChanged)
  4. Create the OnPropertyChanged method to call the PropertyChangedEventHandler event

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

Can someone explain the advantage of this over simply setting:

TextBlock.Text = MyString;

Thanks!

4

3 回答 3

5
  1. Any changes to MyString won't be automatically reflected in your UI.
  2. Your code behind will be littered with "when this event occurs, update these pieces of data", so you'll essentially be writing your own messy data binding logic for each and every view.
于 2013-05-27T10:07:08.050 回答
1

The advantage is that you can both change and display the value in multiple places, without having to update some method to add another TextBlock assignment each time the value changes. Any new display control just binds itself to the property, the rest is automatic.

Now if you really just set the value in one place and show it in one control, then you're right, there's not much point.

于 2013-05-27T10:06:48.903 回答
0

The gain of using Data Binding isn't particularly noticeable for a TextBlock binding to a static string.

However if the value of MyString changes during application runtime it becomes much more useful - especially in a case where the object that owns that property is unaware of the TextBlock. This separation between UI 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 the ListBox.Items to a property that is of type ObservableCollection and the UI will automatically update whenever the content of that collection changes.

于 2013-05-27T10:11:55.867 回答