Created Bindable WindowsFormsHost, but child updat

2019-02-22 08:07发布

问题:

I created ran into a problem where i want to bind a control to a windowsFormsHost control. But as we all know, the Child property is not a DP, so i created a wrapper.

/// <summary>
    ///     Bindable version of windows form hosts
    /// </summary>
    public class BindableWindowsFormsHost : WindowsFormsHost
    {
        /// <summary>
        /// Max value of the textbox
        /// </summary>
        public Control BindableChild
        {
            get { return (Control)GetValue(BindableChildProperty); }
            set 
            {
                SetValue(BindableChildProperty, value);
            }
        }

        // Using a DependencyProperty as the backing store for Max.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty BindableChildProperty =
            DependencyProperty.Register("BindableChild", typeof(Control), typeof(BindableWindowsFormsHost),  new FrameworkPropertyMetadata(new PropertyChangedCallback(OnBindableChildChanged)));

        /// <summary>
        /// Handles changes to the FlyoutWindowSize property.
        /// </summary>
        private static void OnBindableChildChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            ((WindowsFormsHost)d).Child = e.NewValue as Control;
        }
    }

The e.NewValue gets the control I want and sets it properly, BUT i do not see the change being reflected. The child is set, but can't see the windowsFormsHost with new control.

Any one have idea?

Thanks and Regards, Kev84

回答1:

Instead of creating a wrapper you could wrap the WindowsFormsHost in a ContentControl and set its Content property via a binding. That way you avoid the issue with the WindowsFormsHosts Child property not being a dependency property.

Something like this in XAML:

<ContentControl Content="{Binding MyWindowsFormsHost}" />

..and this in your code-behind:

public WindowsFormsHost MyWindowsFormsHost
{   
    get { return new WindowsFormsHost(){Child=myWinformsControl}; }   
}