Binding To Singleton Class Observable Collection Member
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); }
You can keep GetInstance to be a method and use ObjectDataProvider:
<Window.Resources> <ObjectDataProvider x:Key="data" ObjectType="{x:Type local:Logger}" MethodName="GetInstance" /></Window.Resources><ListBox ItemsSource="{Binding Source={StaticResource data},Path=Log}"/>
But again you have to initialize _Log on constructor or GetInstance.