绑定到 WinForms 中的 WPF 托管控件的 DependencyProperty

发布于 2024-09-05 20:04:16 字数 464 浏览 3 评论 0原文

我有一个 WinForms 应用程序,其中包含一些托管 WPF 用户控件的元素(使用 ElementHost)。

我希望能够将 WinForm 的控件属性 (Button.Enabled) 绑定到托管 WPF 用户控件 (SearchResults.IsAccountSelected) 的自定义 DependencyProperty。

是否可以将 System.Windows.Forms.Binding 绑定到 DependencyProperty 管理的属性?

另外,由于我知道 System.Windows.Forms.Binding 监视 INotifyPropertyChanged.PropertyChanged 事件 - DependencyProperty 支持的属性是否会自动触发这些事件,或者我是否必须实现和管理 PropertyChanged 的​​发送手动事件?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

旧人九事 2024-09-12 20:04:16

DependencyObject 未实现 INotifyPropertyChanged,因此如果您采用此路线,则必须手动实现 PropertyChanged 事件的发送。

幸运的是,DependencyObject 确实具有 OnPropertyChanged 方法,因此在 DependencyObject 派生类中实现 INotifyPropertyChanged 非常简单,例如:

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;
}

我想赞同 jsmith 的想法,即直接绑定到 UserControl 属性可能不是最佳途径。在大多数情况下,MVVM 是更好的选择。当然也有例外。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文