wpfvb.netmvvmmultiple-views

WPF MVVM VB.Net multiple views application


Help! It's been a week now I've started to try and build a MVVM application in VB.NET. Unfortunately 98% of the documentation is C# oriented. I found some clues but I still have not all the answers ...

What I want to do: An application with 3 views: loginView, View1 and View2. If no user connected the the loginView is displayed (which is ok). When user is connected, then I should load View1 or View2 regarding his permissions.

It should be quite simple but as I hardly find the pieces of this puzzle I almost lost all of my hair ...

First issue: In the loginView how can I check the user credentials? As I can't bind any property to the PasswordBox, I found some doc saying I should do it this way:

<Button x:Name="btnLogin" Content="Log in"
                Command="{Binding Path=AuthenticateUser}"
                CommandParameter="{Binding ElementName=txtPassword}"/>

But if I managed to execute a command without parameters, I can't find how to execute a command WITH parameters. Any simple idea?

To run a command from a button, I use the relayCommand class found there: Implementing RelayCommand (MVVM) in VB.NET: Syntax problems

So I defined a property like this:

    Dim _relayCmd As New RelayCommand(AddressOf Authentication)
    Public ReadOnly Property AuthenticateUser As ICommand
        Get
            Return _relayCmd
        End Get
    End Property

    ' Authentication method
    Private Sub Authentication(ByVal _passwordBox As PasswordBox)

        'do something...
    End Sub

Second issue: Once the user is connected, how I switch to View1 or View2? I read some doc saying I should use an observablecollection of my views and navigate through it. But I should change the datacontext of my MainWindowView. Still haven't found the right way in VB.

I don't want you to do everything for me instead I would like to find an easy tutorial that can explain clearly how it works in VB.

Thanks for your help!


Solution

  • You could cast the command parameter to a PasswordBox:

    Dim _relayCmd As New RelayCommand(AddressOf Authentication, Function(obj As Object)
    Return True
    End Function)
    Public ReadOnly Property AuthenticateUser As ICommand
        Get
            Return _relayCmd
        End Get
    End Property
    
    Private Sub Authentication(ByVal _passwordBox As Object)
        Dim passwordBox = TryCast(_passwordBox, PasswordBox)
        'do something...
    End Sub
    

    As for your second issue you haven't provided enough details. But please ask another question if you have another issue.