Workaround for inability to bind to a property that belongs to a WindowsFormsHost Child object in C#/XAML app?

后端 未结 3 1215
被撕碎了的回忆
被撕碎了的回忆 2021-01-06 10:17

I have a C# WPF 4.51 app. As far as I can tell, you can not bind to a property belonging to an object that is the child of a WPF WindowsFormsHost control. (If I a

3条回答
  •  旧巷少年郎
    2021-01-06 11:06

    A simple approach here is you can create some dedicated class to contain just attached properties mapping to the properties from your winforms control. In this case I just choose Text as the example. With this approach, you can still set Binding normally but the attached properties will be used on the WindowsFormsHost:

    public static class WindowsFormsHostMap
    {
        public static readonly DependencyProperty TextProperty
            = DependencyProperty.RegisterAttached("Text", typeof(string), typeof(WindowsFormsHostMap), new PropertyMetadata(propertyChanged));
        public static string GetText(WindowsFormsHost o)
        {
            return (string)o.GetValue(TextProperty);
        }
        public static void SetText(WindowsFormsHost o, string value)
        {
            o.SetValue(TextProperty, value);
        }
        static void propertyChanged(object sender, DependencyPropertyChangedEventArgs e)
        {
            var t = (sender as WindowsFormsHost).Child as Scintilla;
            if(t != null) t.Text = Convert.ToString(e.NewValue);
        }
    }
    

    Usage in XAML:

    
        
            
        
    
    

    The Child should of course be a Scintilla, otherwise you need to modify the code for the WindowsFormsHostMap. Anyway this is just to show the idea, you can always tweak it to make it better.

    Note the code above works just for 1 way binding (from view-model to your winforms control). If you want the other way, you need to register some event handler for the control and update the value back to the attached property in that handler. It's quite complicated that way.

提交回复
热议问题