Search code examples
wpflistviewitemsource

Populate my ListView with item source from class


I have this Singleton that hold my ObservableCollection<MyData> as a memeber:

public sealed class Singleton
{
    private static volatile Singleton instance;
    private static object syncRoot = new Object();

    public ObservableCollection<MyData> Files { get; private set; }

    private Singleton()
    {
        Files = new ObservableCollection<MyData>();
    }

    public static Singleton Instance
    {
        get
        {
            if (instance == null)
            {
                lock (syncRoot)
                {
                    if (instance == null)
                        instance = new Singleton();
                }
            }

            return instance;
        }
    }
}

Declaration from main form class:

ObservableCollection<MyData> Files;

And here after the constructor:

Files= Singleton.Instance.Files;

XAML:

<ListView ItemsSource="{Binding Files}" />

Now when the user choose files i want to check each file:

private static void Check(IEnumerable<string> files)
{
    CancellationTokenSource tokenSource = new CancellationTokenSource();
    CancellationToken token = tokenSource.Token;
    Task task = Task.Factory.StartNew(() =>
    {
        try
        {
            Parallel.ForEach(files,
            new ParallelOptions
            {
                MaxDegreeOfParallelism = 1
            },
        file =>
        {
            ProcessFile(file);
        });
        }
        catch (Exception)
        { }

    }, tokenSource.Token,
       TaskCreationOptions.None,
       TaskScheduler.Default).ContinueWith
        (t =>
        {

        }
, TaskScheduler.FromCurrentSynchronizationContext()
);
}

And:

private static void ProcessFile(string file)
{
    // Lets assume that i want to add this file into my `ListView`
    MyData data = new .....
    Singleton.Instance.Files.Add(data);
}

So after this point when i am add files into my list nothing happenning.


Solution

  • Using your code above i was able to reproduce the issue you describe. The problem is that WPF cannot bind to fields, see this question for more details. All you need to do is to change the ObservableCollection<MyData> in the code behind of your main form to a property instead of a field.

    public partial class MainWindow : Window
    {
        public ObservableCollection<MyData> Files { get; private set; }