Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Binding to a WPF hosted control's DependencyProperty in WinForms

I have a WinForms app with some elements that are hosted WPF user controls (using ElementHost).

I want to be able to bind my WinForm's control property (Button.Enabled) to a custom DependencyProperty of the hosted WPF user control (SearchResults.IsAccountSelected).

Is it possible to bind a System.Windows.Forms.Binding to a property managed by a DependencyProperty?

Also, since I know the System.Windows.Forms.Binding watches for INotifyPropertyChanged.PropertyChanged events - will a property backed by a DependencyProperty automatically fire these events or will I have to implement and manage the sending of PropertyChanged events manually?

like image 749
Reddog Avatar asked Dec 08 '25 09:12

Reddog


1 Answers

DependencyObject doesn't implement INotifyPropertyChanged, so if you take this route you will have to implement the sending of PropertyChanged events manually.

Fortunately DependencyObject does have the OnPropertyChanged method, so implementing INotifyPropertyChanged in your DependencyObject-derived class is trivial, for example:

public class MyClass : HeaderedContentControl, INotifyPropertyChanged
{
  protected override void OnPropertyChanged(DependencyPropertyChangedEventArgs e)
  {
    var handler = PropertyChanged;
    if(handler!=null) handler(this, new PropertyChangedEventArgs(e.Property.Name));
    base.OnPropertyChanged(e);
  }
  public event PropertyChangedEventHandler PropertyChanged;
}

I'd like to echo jsmith's thought that binding directly to a UserControl property may not be the best route to take. In most cases MVVM is a better way to go. There are exceptions, of course.

like image 71
Ray Burns Avatar answered Dec 09 '25 23:12

Ray Burns