我有一个C#WPF 4.51应用程序.据我所知,您不能绑定属于WPF WindowsFormsHost控件的子对象的属性. (如果我在这个假设中错了,请告诉我该怎么做):Bind with WindowsFormsHost在我的例子中,我有一个包含WindowsFormsHo...
                
我有一个C#WPF 4.51应用程序.据我所知,您不能绑定属于WPF WindowsFormsHost控件的子对象的属性. (如果我在这个假设中错了,请告诉我该怎么做):
Bind with WindowsFormsHost
在我的例子中,我有一个包含WindowsFormsHost控件的页面,其Child对象是ScintillaNET编辑器控件:
https://github.com/jacobslusser/ScintillaNET
    <WindowsFormsHost x:Name="wfhScintillaTest"
                      Width="625"
                      Height="489"
                      Margin="206,98,0,0"
                      HorizontalAlignment="Left"
                      VerticalAlignment="Top">
        <WindowsFormsHost.Child>
            <sci:Scintilla x:Name="scintillaCtl" />
        </WindowsFormsHost.Child>
    </WindowsFormsHost>
子控件工作正常.如果它是一个普通的WPF控件,我会将Scintilla编辑器控件的Text属性绑定到我的ViewModel中的某个字符串属性,这样我只需更新Scintilla编辑器控件的内容即可更新该字符串属性.
但由于我无法绑定属于WindowsFormsHost子对象的属性,我正在寻找一种不完全笨拙或笨拙的策略/解决方案.以前是否有人遇到过这种情况并且有一个合理的策略来解决我的绑定/更新问题?
解决方法:
这里一个简单的方法是,您可以创建一些专用类,以包含映射到winforms控件中的属性的附加属性.在这种情况下,我只选择Text作为示例.使用这种方法,您仍然可以正常设置Binding,但附加属性将在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);
    }
}
在XAML中的用法:
<WindowsFormsHost x:Name="wfhScintillaTest"
                  Width="625"
                  Height="489"
                  Margin="206,98,0,0"
                  HorizontalAlignment="Left"
                  VerticalAlignment="Top"
                  local:WindowsFormsHostMap.Text="{Binding yourTextProp}"
    >
    <WindowsFormsHost.Child>
        <sci:Scintilla x:Name="scintillaCtl"/>
    </WindowsFormsHost.Child>
</WindowsFormsHost>
Child当然应该是Scintilla,否则你需要修改WindowsFormsHostMap的代码.无论如何,这只是为了展示这个想法,你总是可以调整它以使其更好.
请注意,上面的代码仅适用于单向绑定(从视图模型到winforms控件).如果您想要另一种方式,则需要为控件注册一些事件处理程序,并将值更新回该处理程序中的附加属性.这种方式非常复杂.
本文标题为:无法绑定到属于C#/ XAML应用程序中的WindowsFormsHost子对象的属性的解决方法?
				
        
 
            
        - Unity Shader实现模糊效果 2023-04-27
 - WPF使用DrawingContext实现绘制刻度条 2023-07-04
 - C# 使用Aspose.Cells 导出Excel的步骤及问题记录 2023-05-16
 - Unity3D实现渐变颜色效果 2023-01-16
 - 如何使用C# 捕获进程输出 2023-03-10
 - 在C# 8中如何使用默认接口方法详解 2023-03-29
 - user32.dll 函数说明小结 2022-12-26
 - c# 模拟线性回归的示例 2023-03-14
 - Oracle中for循环的使用方法 2023-07-04
 - .NET CORE DI 依赖注入 2023-09-27
 
						
						
						
						
						
				
				
				
				