Ahsan
Ahsan

Reputation: 658

Variables which need to be live across the application in WPF

I am developing a WPF application. I need some variables/information not to destroy until user closes that application. Which method is best? Static Class with static variables? Moreover what is the best practice in this scenario?

Upvotes: 2

Views: 1131

Answers (3)

Miro Bucko
Miro Bucko

Reputation: 1133

You can also create static class and reference it in xaml like this:

namespace MyNamespace
{
    public static class Globals
    {
        public static double SomeVariable { get { return 1.0; } }
    }
}

Then access it from xaml like this:

<UserControl Width="{x:Static globals:Globals.SomeVariable}" />

where globals is defined at top top of your xaml like following:

<Window x:Class="MyNamespace.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:globals="clr-namespace:MyNamespace">
</Window>

Upvotes: 1

Anatoliy Nikolaev
Anatoliy Nikolaev

Reputation: 22702

In this situation, you can use a static Class with static fields. He is never released, it doesn't have any destructors, and is not involved in garbage collection.

If you want to a normal class stayed alive, you can use the method GC.KeepAlive():

SampleClass sample = new SampleClass();

//... Somewhere in the end ...

GC.KeepAlive(sample);

Here, KeepAlive() creates a reference to your instance of the class in order to garbage collection think, that he still in use in your application. The purpose of the KeepAlive() is to ensure the existence of a reference to an object that is at risk of being prematurely reclaimed by the GC.

Quote from MSDN:

This method references the obj parameter, making that object ineligible for garbage collection from the start of the routine to the point, in execution order, where this method is called. Code this method at the end, not the beginning, of the range of instructions where obj must be available.

The KeepAlive method performs no operation and produces no side effects other than extending the lifetime of the object passed in as a parameter.

Alternatively, information can be stored in the WPF-application settings. Especially if the information is important and should not be lost after system failure or reboot.

Settings located approximately here Project -> Properties -> Parameters. Example with setting new value:

MyProject.Properties.Settings.Default.MyButtonColor = "Red";

Saving is performed as follows:

MyProject.Properties.Settings.Default.Save();

It also possible using Binding with properties, indicating class of the settings in Source:

xmlns:properties="clr-namespace:MyProject.Properties"

<TextBlock Text="{Binding Source={x:Static properties:Settings.Default},
                          Path=MyButtonColor,
                          Mode=TwoWay}" />

For more information about using settings in WPF, please see:

User settings in WPF

A configurable Window for WPF

Saving user color settings of a clicked Button in WPF

Upvotes: 2

Rachit
Rachit

Reputation: 136

I belive what you can do is to write a class which would hold variables for you as the session object does in ASP .net . You can do something like

public static class ApplicationState
{
    private static Dictionary<string, object> _values =
               new Dictionary<string, object>();
    public static void SetValue(string key, object value)
    {
        if (_values.ContainsKey(key))
        {
            _values.Remove(key);
        }
        _values.Add(key, value);
    }
    public static T GetValue<T>(string key)
    {
        if (_values.ContainsKey(key))
        {
            return (T)_values[key];
        }
        else
        {
            return default(T);
        }
    }
}

To save a variable:

ApplicationState.SetValue("MyVariableName", "Value");

To read a variable:

MainText.Text = ApplicationState.GetValue<string>("MyVariableName");

This would be accesses all through yuor application and would remain in memory throughout.

Upvotes: 3

Related Questions