what
what

Reputation: 373

Session in WPF?

In ASP.NET, I can do Session["something"] = something;, and then I can retrieve in another page the value of the session. Is there a Session in WPF that would allow me to do the same in ASP.NET? I notice there is no session in WPF because there is state. Because I got many user control pages, I need to get its values and display it on the MainWindow.

Is there anything similar to Session in WPF?

Some resources say to use cookies. How do I do that? mine Is a WPF application not a WPF web application?

Upvotes: 17

Views: 19515

Answers (4)

Imtiyaz Uddin
Imtiyaz Uddin

Reputation: 1

Try the following:

System.Windows.Application.Current.Properties["Something"] = Something;

I Used this many times in my project,

Upvotes: -2

G.Dealmeida
G.Dealmeida

Reputation: 335

In my opinion, the best way to do it will be to store it in the current properties of your application like this :

Application.Current.Properties["stuff"]

You can store any kind of object, but don't abuse it.

I will personally use this kind of tricks only if I have no other way to share data (same advice than Grant Winney)

I prefer using Resources for translation or images and properties for other flag/data just to separate things a little

Upvotes: 1

Grant Winney
Grant Winney

Reputation: 66439

One possibility is to use:

Application.Current.Resources["something"] = something;

I wouldn't get into the habit of using that too frequently though. I think it's generally for data that's being stored once (such as styles) and then just referenced from other points in the application. Everything in your app reading/writing to some globally shared piece of data is poor practice and could make debugging tough.

Upvotes: 8

xxbbcc
xxbbcc

Reputation: 17327

If I understand your question correctly, you just need some kind of global storage for certain values in your program.

You can create a static class with public static properties for the various values that you need to store and be able to globally access inside your application. Something like:

public static class Global
{
    private string s_sSomeProperty;

    static Globals ()
    {
        s_sSomeProperty = ...;
        ...
    }

    public static string SomeProperty
    {
        get
        {
            return ( s_sSomeProperty );
        }
        set
        {
            s_sSomeProperty = value;
        }
    }

    ...
}

This way you can just write Global.SomeProperty anywhere in your code where the Global class is available.

Of course, you'd need validation and - if your application is multithreaded - proper locking to make sure your global (shared) data is protected across threads.

This solution is better than using something like session because your properties will be strongly typed and there's no string-based lookup for the property value.

Upvotes: 17

Related Questions