SharpGL + WPF:Draw是从未调用过的事件

时间:2018-03-25 14:58:53

标签: c# wpf sharpgl

我正在尝试使用WPF构建SharpGL应用程序,但无法集成视图模型。

我将 OpenGLControl的 DataContext 绑定到 ViewModel 中的OpenGLControl 属性,并在视图模型中为绘图函数创建事件,但他们永远不会被召唤。

OpenGLControl 只显示为黑屏。当我在 xaml.cs 文件后面的代码中实现绘图功能时,它可以工作,但我真的想使用viewModel。

<Window.DataContext>
    <local:ViewModel />
</Window.DataContext>

[...]

<StackPanel Orientation="Horizontal">
        <GroupBox Width="80" Header="Controls">
            <StackPanel>
                <TextBox Text="{Binding TranslationX}" />
                <TextBox Text="{Binding TranslationY}" />
                <TextBox Text="{Binding TranslationZ}" />
            </StackPanel>

        </GroupBox>
        <sharpGL:OpenGLControl x:Name="GLControl" DataContext="{Binding OpenGLControl}" MinWidth="350"/>
</StackPanel>

ViewModel代码:

    private OpenGLControl openGLControl = new OpenGLControl();
    public OpenGLControl OpenGLControl
    {
        get
        {
            return openGLControl;
        }
        set
        {
            openGLControl = value;
            NotifyPropertyChanged(); //Custom implementation of 
                                     //INotifyPropertyChanged
        }
    }
    public ViewModel()
    {
        OpenGLControl.OpenGLDraw += drawEvent;
    }
    private void drawEvent(object sender, OpenGLEventArgs args)
    {
        draw(args.OpenGL); // draws a number of vertices, works when used in 
                           //  code behind
    }

1 个答案:

答案 0 :(得分:0)

A DataContext in WPF controls how and to what exact Properties a Binding will bind to. What you are doing by setting a DataContext like <sharpGL:OpenGLControl DataContext="{Binding OpenGLControl}" /> is essentially this: When searching for properties required by a Binding, search inside the OpenGLControl ViewModel.

This does not work because your are creating two OpenGLControl's one which is created in the XAML via <sharpGL:OpenGLControl/> and a second one which is created inside your ViewModel. Next you set events for your ViewModel (which is not visible) and instruct the OpenGLControl created in the XAML that it should search for data that is required by any Binding to look inside the OpenGLControl in the ViewModel.

Since OpenGLControl is a Control, you should probably not think of it as a good canditate for a ViewModel. Instead try to create an eventhandler in the window and forward all draw event callbacks from the window to your ViewModel by e.g. calling a delegate.