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

Ian*_*ose 3 data-binding wpf mvvm winforms

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

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

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

jon*_*ers 6

我认为你必须将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); }
    }
}
Run Code Online (Sandbox Code Playgroud)

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


Ian Ringrose补充道:

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

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

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

  • 抱歉,_control声明为静态?你能给我一个使用包装类的样本吗? (2认同)