0

I'm trying to build a SharpGL app with WPF, but have trouble integrating a view model.

I bind the DataContext of an OpenGLControl to an OpenGLControl property in my ViewModel and create events for the drawing functions in the view model, but they never get called.

The OpenGLControl just appears as a black screen. When I just implement the drawing function in a code behind xaml.cs file it works, but I really want to use a 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 code:

    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
    }
Héctor M.
  • 2,302
  • 4
  • 17
  • 35

1 Answers1

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.

ZiggZagg
  • 1,397
  • 11
  • 16