gpt4 book ai didi

c# - WPF MVVM WinformsHost 与 OpenGL 控制

转载 作者:行者123 更新时间:2023-11-30 16:59:23 29 4
gpt4 key购买 nike

我正在使用 MVVM 开发 WPF 应用程序。在此应用程序中,我需要一个 OpenGL 控件(我使用的是 OpenTK)。当前在 WPF 中获取 OpenGL 的唯一有用方法是使用 WindowsFormsHost。到这里为止,没有问题。

要向我的场景添加内容,我需要访问我的 View 中的 OpenGL-Control。当然我想添加和编辑 ViewModel 中的内容。那么,如何在不违反 MVVM 模式的情况下访问 OpenGL 控件?

我正在使用一个场景对象,它可以在 View 中初始化,然后需要以某种方式传输到 ViewModel。我尝试使用 WindowsFormsHost 的 Tag-property 但没有成功(下面比较)。 ViewModel 中的属性未更新。

有什么想法吗?

XAML

<UserControl x:Class="FancyOpenGlControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<WindowsFormsHost x:Name="WindowsFormsHost" Tag="{Binding Scene, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />
</UserControl>

C#

public FancyOpenGlControl()
{
this.InitializeComponent();

this.glControl = new OpenGLControl();
this.glControl.Dock = DockStyle.Fill;
this.WindowsFormsHost.Child = this.glControl;

this.glControl.HandleCreated += this.GlControlOnHandleCreated;
}

private void GlControlOnHandleCreated(object sender, EventArgs eventArgs)
{
this.WindowsFormsHost.Tag = new Scene(this.glControl);

// Doesn't work.
//BindingExpression bindingExpression = this.WindowsFormsHost.GetBindingExpression(TagProperty);
//if (bindingExpression != null)
//{
// bindingExpression.UpdateSource();
//}
}

最佳答案

我能想到两种选择。

1) 直接从后面的 View 代码中设置您的 View 模型属性。您需要执行此操作以响应 View 的 DataContextChanged 事件,因为您的 ViewModel 尚未连接到 View 的构造函数中。这也意味着将 DataContext 转换为已知类型的 ViewModel。我真的没有问题,但有些人有。

private void FancyOpenGlControl_DataContextChanged(object sender, DependencyPropertyChangedEventArgs e)
{
var vm = this.DataContext as MyViewModel;

if (vm != null)
vm.GlControl = this.glControl;
}

2) 如果你更喜欢稍微松散的耦合,那么你可以在你的 View 上创建一个依赖属性,并在你创建它时将你的 glControl 分配给它。然后,您可以像往常一样将该属性绑定(bind)到您想要的任何 ViewModel 属性。例如:

代码隐藏:

public static readonly new DependencyProperty GControlProperty =
DependencyProperty.Register("GLControl", typeof(OpenGLControl), typeof(FancyOpenGlControl), new PropertyMetadata(null));

public OpenGLControl GLControl
{
get { return (OpenGLControl )GetValue(DocumentProperty); }
set { SetValue(GLControlProperty , value); }
}

public FancyOpenGlControl()
{
this.InitializeComponent();

this.GLControl= new OpenGLControl();
this.GLControl.Dock = DockStyle.Fill;
this.WindowsFormsHost.Child = this.GLControl;
}

XAML:

<UserControl x:Class="FancyOpenGlControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
GLControl="{Binding VMControlProperty}">
<WindowsFormsHost x:Name="WindowsFormsHost"/>

关于c# - WPF MVVM WinformsHost 与 OpenGL 控制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23733822/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com