Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Binding To Singleton Class Observable Collection Member

I just can't seem to figure this out. I found some similar Questions here but either I can't figure out the right direction for my approach or I am doing something completly wrong.

My Application has a Singleton Class Logger, which saves Log messages from every class in my program.

public class Logger
{
    private Logger()
    {

    }

    private static volatile Logger instance;

    public static Logger GetInstance()
    {
        // DoubleLock
        if (instance == null)
        {
            lock (m_lock)
            {
                if (instance == null)
                {
                    instance = new Logger();
                }
            }
        }
        return instance;
    }

    //Helper for Thread Safety
    private static object m_lock = new object();

    private ObservableCollection<string> _Log;

    public ObservableCollection<string> Log
    {
        get { return _Log; }
    }

    public void Add(string text)
    {
        if (_Log == null)
            _Log = new ObservableCollection<string>();

        Log.Add(DateTime.Now.ToString() + " " + text);
    }

    public void Clear()
    {
        _Log.Clear();
    }

}

Now I want to bind Log to ListBox in my MainWindow, but I can't figure out the right Binding

<ListBox Name="lstboxLog" Grid.Row="2" Margin="10,0,10,10" ItemsSource="{Binding Source={x:Static tools:Logger.Log}}" Height="100" />

tools is the namespace of the singleton class in my XAML. I'm sure this is simpler than I think, but I am just overlooking something.

like image 221
metacircle Avatar asked Apr 20 '12 07:04

metacircle


1 Answers

Make your GetInstance() method to a get property. And to be on the sure side instantiate your log Observable Collection before you access it. That way the binding won't be overriden if it is bound before you call your first Add() method on it.

XAML:

ItemsSource="{Binding Source={x:Static tools:Logger.Instance}, Path=Log}"

Logger:

public static Logger Instance
    {
      get
      {
      // DoubleLock
      if (instance == null)
      {
        lock (m_lock)
        {
          if (instance == null)
          {
            instance = new Logger();
          }
        }
      }
      return instance;
      }
    }

    //Helper for Thread Safety
    private static object m_lock = new object();

    private ObservableCollection<string> _Log;

    public ObservableCollection<string> Log
    {
      get
      {
        if (_Log == null)
        { 
          _Log = new ObservableCollection<string>();
        }
        return _Log;
      }
    }

    public void Add(string text)
    {
      Log.Add(DateTime.Now.ToString() + " " + text);
    }
like image 109
SvenG Avatar answered Nov 13 '22 02:11

SvenG