繁体   English   中英

如何数据绑定到WPF控件中托管的Winform控件?

[英]How do I databind to a Winform control that is hosted in a WPF control?

我只是考虑将我们的一个自定义控件转换为WPF,但它使用另一个自定义控件来编写Winforms。

因为没有MVVM使用WPF没什么意义。 如何数据绑定到WPF控件中使用的Winforms控件。

(我没有太多的WPF经验,所以我可能完全忽略了这一点)

我认为你必须将WinForms控件包装在暴露DependencyProperties或至少实现INotifyPropertyChanged的类中。

所以你有一个类,如:

public class WinFormsWrapper : WindowsFormsHost
{
   //You'll have to setup the control as needed
   private static MyWinFormsControl _control;

   public static readonly DependencyProperty IsSpinningProperty = DependencyProperty.Register("IsSpinning", typeof(bool), typeof(WinFormsWrapper), 
        new FrameworkPropertyMetadata(_control.IsSpinning, new PropertyChangedCallback(IsSpinning_Changed)));

    private static void IsSpinning_Changed(DependencyObject sender, DependencyPropertyChangedEventArgs e)
    {
        _control.IsSpinning = (bool)e.NewValue;
    }

    public bool IsSpinning
    {
        get { return (bool)GetValue(IsSpinningProperty); }
        set { SetValue(IsSpinningProperty, value); }
    }
}

假设您的WinForms控件上有一个IsSpinning属性。 根据您的需要,实现INotifyPropertyChanged而不是使用DependencyProperties可能更简单。


Ian Ringrose补充道:

这个示例代码显然是错误的(请参阅有关_control是静态的评论),但显示了如何解决问题。 因为我目前没有使用WPF,所以我不会编辑代码,因为我无法测试我的编辑。

我将这个答案作为公认的答案,因为它包含解决问题所需的信息。

我已将此添加到答案中,因为评论有时会被删除,这是来自谷歌搜索的人的吸引力观点。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM