-1

I have a simple WPF MVVM application that consist of a MainWindow and two UserControl (Login, Register) and Database Table Users. I want to bind the user control to main window like, if in my sql table data already exist then Login user control will be displayed else Register user control.

Sabyasachi Mishra
  • 1,677
  • 2
  • 31
  • 49
  • You can do like pass your all sql code in to main loading events if user exists then login usercontrol respond and user not exists then register usercontrols comes. – Dhru 'soni Mar 24 '15 at 07:46
  • Pretty sure you'll be able to address this by binding the Visibility properties of your UserControls to properties in your ViewModel as shown here: http://stackoverflow.com/questions/10607548/wpf-bind-usercontrol-visibility-to-a-property . – goobering Mar 24 '15 at 08:43

2 Answers2

1

If you look at my answer to the WPF MVVM navigate views question, you'll find a way to display different views in a single place. The answer to your question is for you to implement a similar setup in which you can display either your Login view or your Register view:

public BaseViewModel ViewModel { get; set; }

...

<DataTemplate DataType="{x:Type ViewModels:LoginViewModel}">
    <Views:LoginView />
</DataTemplate>
<DataTemplate DataType="{x:Type ViewModels:RegisterViewModel}">
    <Views:RegisterView />
</DataTemplate>

When your main view model loads, you simply need to check whether you have any data in the database for the current user and then choose to display the relevant view... perhaps something like this:

ViewModel = IsUsernameRegistered(username) ? new LoginView() : new RegisterView();
Community
  • 1
  • 1
Sheridan
  • 68,826
  • 24
  • 143
  • 183
0

I got my answer as Write the below method in App.xaml.cs and delete StartupUri="" from App.xaml

    protected override void OnStartup(StartupEventArgs e)
    {
        base.OnStartup(e);

        var con = new SqlConnection
        {
            ConnectionString = "Data Source=localhost;Initial Catalog=demo;User ID=sa;Password=mypassword;"
        };
        con.Open();
        const string chkadmin = "select COUNT(*) from dbo.Registrations";
        var command = new SqlCommand(chkadmin, con);
        int count = Convert.ToInt32(command.ExecuteScalar());
        if (count == 0)
        {
            var reg = new AdminUser(); //this is the Registration window class
            this.MainWindow = reg;
            reg.Show();
        }
        else
        {
            var win = new Home(); //this is the Home window class
            this.MainWindow = win;
            win.Show();
        }
    }
Sabyasachi Mishra
  • 1,677
  • 2
  • 31
  • 49