سؤال

When I log into my application, I pass the cUserEntity class which holds all the details of the logged in user, including UserID and Username, to the Dashboard form. From here, I can continue to pass the details around from class to class and form to form. For example (Ignore the generic bit in this example):

Login:

 xamlDashboard Manager = new xamlDashboard(_loggedInUser);
 Generic Gen = new Generic(_loggedInUser);
 Manager.Show();

Dashboard:

cUserEntity _loggedInUser;

  public xamlDashboard(cUserEntity loggedInUser)
    {

        InitializeComponent();

        _loggedInUser = loggedInUser;
    }

However, I have a Generic.Xaml page which creates a button at the top of every window. Behind the Generic.xaml is a Generic class, which holds the click_event for the created button. The click_event opens a new window to another form.

Now, I need that other form to have the logged in user details, and to do that, I assume I need to pass to the Generic.Xaml and then pass from there to the new form via the click_event. However, as I've read up and noticed, it doesn't seem to be possible as you can't pass a type to a Generic during runtime.

What I hoped to achieved (which failed):

public partial class Generic
{
    cUserEntity _loggedInUser;

    public Generic(cUserEntity loggedInUser)
    {
        _loggedInUser = loggedInUser;
    }

    private void btnHelp_Click(object sender, RoutedEventArgs e)
    {
        xamlHelp help = new xamlHelp(_loggedInUser);
        help.Show();
    }
}

Therefore, what is the best and most efficient method to be able to do this, and would appreciate examples, if possible.

هل كانت مفيدة؟

المحلول

It would be alot simpler to create a singleton object to store your logged in user...

public class UserAccount
{
   private static User _currentUser;

   private UserAccount() {}

   public static User CurrentUser
   {
      set
      {
         _currentUser = value;
      }

      get 
      {
         return _currentUser;
      }
   }
}

Then after login you would do this...

// Set the current User
UserAccount.CurrentUser = user;

Then in any class you need the currently logged in user... you could do...

var user = UserAccount.CurrentUser;

Obviously you would need to implement your own business rules around this but the concept is what I am trying to get across here, a static single instance of the user that can be accessed from anywhere.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top