Databinding to CLR property in code-behind

前端 未结 5 1352
隐瞒了意图╮
隐瞒了意图╮ 2021-02-15 20:18

Binding to a Dependency Property is easy in code-behind. You just create a new System.Windows.Data.Binding object, and then call the target dependency object\'s

5条回答
  •  情话喂你
    2021-02-15 21:22

    For this to be possible, the property must be one for which you are writing the setter (so, not a property defined in code you can't change).
    Then the solution is Implement Property Change Notification.

    Sample code from above link:

    using System.ComponentModel;
    
    namespace SDKSample
    {
      // This class implements INotifyPropertyChanged
      // to support one-way and two-way bindings
      // (such that the UI element updates when the source
      // has been changed dynamically)
      public class Person : INotifyPropertyChanged
      {
          private string name;
          // Declare the event
          public event PropertyChangedEventHandler PropertyChanged;
    
          public Person()
          {
          }
    
          public Person(string value)
          {
              this.name = value;
          }
    
          public string PersonName
          {
              get { return name; }
              set
              {
                  name = value;
                  // Call OnPropertyChanged whenever the property is updated
                  OnPropertyChanged("PersonName");
              }
          }
    
          // Create the OnPropertyChanged method to raise the event
          protected void OnPropertyChanged(string name)
          {
              PropertyChangedEventHandler handler = PropertyChanged;
              if (handler != null)
              {
                  handler(this, new PropertyChangedEventArgs(name));
              }
          }
      }
    }
    

    In that implementation, each property setter must call

    OnPropertyChanged("YourPropertyName");
    

    Or for a slightly different implementation, that avoids having to re-enter the property name as a string parameter, see my answer here.
    There, I also mention Fody/PropertyChanged, TinyMvvm, and MvvmCross as libraries that can help implement this pattern.
    (I'm working in Xamarin Forms, but I think those are all useable from WPF as well; they are based on System.ComponentModel namespace.)

提交回复
热议问题