How does WPF INotifyPropertyChanged work?

后端 未结 1 849
醉梦人生
醉梦人生 2020-11-30 02:52

This is a typical INotifyPropertyChanged implementation for using Binding in WPF/C#.

namespace notifications.ViewModel
{
    class MainViewModel : INotifyPro         


        
相关标签:
1条回答
  • 2020-11-30 03:07

    How does this call activates ? What's the C#'s magic behind this to make it possible?

    This code creates a Binding object which links the TextBlock's Text property to the ViewModel property. It also adds an event handler to the ViewModel's PropertyChanged event to update the text value when the ViewModel fires the PropertyChanged event (with the right property).

    Why is if (PropertyChanged != null) necessary? Who sets up the PropertyChanged to what value?

    If the PropertyChanged event is null, then firing it will cause a NullReferenceException.

    The meaning of Mode=TwoWay looks like that it not only can signal the change, but also updates the content when other Binding element with the same name in binding changes, then what about OneWay mode? Can we set a Binding as source only or target only?

    The binding modes are:

    • TwoWay: Changes the bound value when the ViewModel property changes and vice versa
    • OneWay: Changes the bound value when the ViewModel property changes only
    • OneWayToSource: Changes the ViewModel property when the bound value changes only
    • OneTime: Sets the bound value to the value of the ViewModel property just when the application is created or the data context changes.

    You can read more about them here: http://msdn.microsoft.com/en-us/library/system.windows.data.bindingmode.aspx

    0 讨论(0)
提交回复
热议问题