WPF: Binding a Label to a class property

后端 未结 2 619
心在旅途
心在旅途 2021-02-04 00:05

I\'m trying to get the content of a label to bind to the string property of a class instance without much success.

XAML:



        
2条回答
  •  太阳男子
    2021-02-04 00:24

    You may make your MyFoo a dependency property and set the DataContext to your Window1 instance:

    
    

    See this article for more details.

    Making MyFoo a dependency property is not compulsory. it may work with just a property if you set the property value before assigning the DataContext. (But never with a field.) However if you want the labels to pick up the changing values of W1 and W2 (or you don't know/care if the values are set before or after assigning the DataContect), you need Foo to be either a DependencyObject, or implement interface INotifyPropertyChanged.

提交回复
热议问题