Search code examples
wpfvb.netuser-controlscaliburn.micro

Binding UserControl to ViewModel (Caliburn Micro WPF)


I am creating a login form that will be used by many different applications. The login will always have the same logic, so I'd like to bind a viewmodel and do all logic there (Retrieving login info from database, etc). I created a new UserControl, MainView and a ViewModel, MainViewModel both of which are in a Login namespace.

The form continues to run everything in the code-behind, but nothing in the VM. Is there another way of binding that I am not aware of?

Code-Behind MainView.Xaml.vb

Imports Caliburn.Micro

Namespace Login
   Public Class MainView

      Public Sub New()
        MsgBox("TEST code-behind")
      End Sub

   End Class
End Namespace

VM MainViewModel.vb

Imports Caliburn.Micro

Namespace Login
    Public Class MainViewModel
        Inherits PropertyChangedBase

        Public Sub New()
            MsgBox("TEST ViewModel")
        End Sub

    End Class
End Namespace

Xaml

<UserControl x:Class="Login.MainView"
         xmlns:cal="http://www.caliburnproject.org"
         xmlns:local="clr-namespace:cLogin.Login"
         cal:Bind.Model="cLogin.Login.MainViewModel" (not sure if needed due to naming)
         ... >

EDIT This is how I have added the UserControl as a separate window before the user is logged in, I can see the content, but none of the properties inside the ViewModel bind

Dim login As New Window
    With login
        .WindowStyle = WindowStyle.None
        .ResizeMode = ResizeMode.NoResize
        .SizeToContent = SizeToContent.WidthAndHeight
        .Content = New MainView()
    End With

login.ShowDialog()

Solution

  • Since you are creating the window explicitly, you also need to explicitly set its DataContext:

    Dim login As New Window
        With login
            .WindowStyle = WindowStyle.None
            .ResizeMode = ResizeMode.NoResize
            .SizeToContent = SizeToContent.WidthAndHeight
            .Content = New MainView()
            .DataContext = New MainViewModel()
    End With
    

    You should also bind the attached Bind.Model property to the DataContext in the view:

    cal:Bind.Model="{Binding}"