views:

1192

answers:

1

Hi all,

I have a class that has two ObservableCollection< TimeValue >'s, where TimeValue is a custom DateTime/Value pairing with change-notification (via INotifyPropertyChanged). I call these Targets and Actuals.

When I bind these to a chart, everything works perfectly, and I get two LineSeries. If I bind one of them to a DataGrid, with a column for "Date" and a column for "Value", works perfectly again. I even get the TwoWay binding that I need.

However, I need to have a DataGrid that has a "Date" column, and a column each for Targets and Actuals. The problem is that I need to list ALL dates in a range, whereas some of these dates may not have corresponding values in Targets, Actuals, or both.

So, I decided I would do a MultiBinding that takes Targets and Actuals as input, and outputs a combined TimeSeriesC, with null values whenever either of the originals had no value.

It works, but does not respond to any changes in the underlying data.

This works fine (binding to one ObservableCollection):

<ctrls:DataGrid Grid.Row="1" Height="400" AutoGenerateColumns="False" CanUserDeleteRows="False" SelectionUnit="Cell">
<ctrls:DataGrid.ItemsSource>
 <Binding Path="Targets"/>
 <!--<MultiBinding Converter="{StaticResource TargetActualListConverter}">
  <Binding Path="Targets"/>
  <Binding Path="Actuals"/>
 </MultiBinding>-->
</ctrls:DataGrid.ItemsSource>
<ctrls:DataGrid.Columns>
 <ctrls:DataGridTextColumn Header="Date" Binding="{Binding Date,StringFormat={}{0:ddd, MMM d}}"/>
 <ctrls:DataGridTextColumn Header="Target" Binding="{Binding Value}"/>
 <!--<ctrls:DataGridTextColumn Header="Target" Binding="{Binding Value[0]}"/>
 <ctrls:DataGridTextColumn Header="Actual" Binding="{Binding Value[1]}"/>-->
</ctrls:DataGrid.Columns>

This works, but only when first initialized. No response to change-notification:

<ctrls:DataGrid Grid.Row="1" Height="400" AutoGenerateColumns="False" CanUserDeleteRows="False" SelectionUnit="Cell">
<ctrls:DataGrid.ItemsSource>
 <!--<Binding Path="Targets"/>-->
 <MultiBinding Converter="{StaticResource TargetActualListConverter}">
  <Binding Path="Targets"/>
  <Binding Path="Actuals"/>
 </MultiBinding>
</ctrls:DataGrid.ItemsSource>
<ctrls:DataGrid.Columns>
 <ctrls:DataGridTextColumn Header="Date" Binding="{Binding Date,StringFormat={}{0:ddd, MMM d}}"/>
 <!--<ctrls:DataGridTextColumn Header="Target" Binding="{Binding Value}"/>-->
 <ctrls:DataGridTextColumn Header="Target" Binding="{Binding Value[0]}"/>
 <ctrls:DataGridTextColumn Header="Actual" Binding="{Binding Value[1]}"/>
</ctrls:DataGrid.Columns>

And here is my IMultiValueConverter:

class TargetActualListConverter : IMultiValueConverter
{
    public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        TimeSeries<double> Targets = values[0] as TimeSeries<double>;
        TimeSeries<double> Actuals = values[1] as TimeSeries<double>;
        DateTime[] range = TimeSeries<double>.GetDateRange(Targets, Actuals);//Get min and max Dates
        int count = (range[1] - range[0]).Days;//total number of days
        DateTime currDate = new DateTime();
        TimeSeries<double?[]> combined = new TimeSeries<double?[]>();
        for (int i = 0; i < count; i++)
        {
            currDate = range[0].AddDays(i);
            double?[] vals = { Targets.Dates.Contains(currDate) ? (double?)Targets.GetValueByDate(currDate) : null, Actuals.Dates.Contains(currDate) ? (double?)Actuals.GetValueByDate(currDate) : null };
            combined.Add(new TimeValue<double?[]>(currDate, vals));
        }
        return combined;
    }

    public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture)
    {
        TimeSeries<double?[]> combined = value as TimeSeries<double?[]>;
        TimeSeries<double> Targets = new TimeSeries<double>();
        TimeSeries<double> Actuals = new TimeSeries<double>();

        foreach (TimeValue<double?[]> tv in combined)
        {
            if(tv.Value[0]!=null)
                Targets.Add(new TimeValue<double>(tv.Date,(double)tv.Value[0]));
            if (tv.Value[1] != null)
                Actuals.Add(new TimeValue<double>(tv.Date, (double)tv.Value[1]));
        }
        TimeSeries<double>[] result = { Targets, Actuals };
        return result;

    }
}

I can't be too far off, since it displays the values.

What am I doing wrong? Or, alternatively, is there an easier way of doing this?

Thanks all!

+1  A: 

Looks like this is caused by the converter. ObservableCollection implements INotifyCollectionChanged, which notifies the UI when there is a change to the collection (Add/Remove/Replace/Move/Reset). These are all changes to the collection, not the contents of the collection, and so the updates you were seeing before were due to your class implementing INotifyPropertyChanged. Because the MultiCoverter is returning a new collection of new objects, the data in the initial collections will not propagate to these, since there's no bindings to the original objects for them to notify.

The first thing I would suggest is to take a look at the CompositeCollection Element and see if that will fit your needs.

Instead of setting the ItemsSource as you are, you could maintain the original objects with something like:

<ctrls:DataGrid.ItemsSource>
    <CompositeCollection>
         <CollectionContainer Collection="{Binding Targets}" />
            <CollectionContainer Collection="{Binding Actuals}" />
       </CompositeCollection>
</ctrls:DataGrid.ItemsSource>

(I'm assuming 'does not respond to any changes in the underlying data' refers to changing the values, not modifying the collection, if I'm incorrect let me know and I'll take a deeper look at it.)

Edit Additions
In the case that that doesn't work an alternative is to write a new class that will wrap both the Target and Actual collections. Then a single ObservableCollection can be created using these wrappers. This is actually a better method over using a ValueConverter or using a CompositeCollection. With either you loose some of the functionality that was originally present. By using a value converter to recreate a collection, it no longer is bound directly to the original objects and so property notification may be lost. By using the CompositeCollection, you no longer have a single collection that can be iterated through or modified with add/delete/move etc, as it has to know which collection to operate upon.

This type of wrapping functionality can be quite useful in WPF, and is a very simplified version of a ViewModel, a part of the M-V-VM design pattern. It can be used when you don't have access to the underlying classes to add INotifyPropertyChanged or IDataErrorInfo, and can also help add additional functionality such as state and interaction to the underlying models.

Here's a short example demonstrating this functionality where both of our initial classes have the same Name property and don't implement INotifyPropertyChanged that is not shared between them.

public partial class Window1 : Window
{
    public Window1()
    {
        InitializeComponent();

        Foo foo1 = new Foo { ID = 1, Name = "Foo1" };
        Foo foo3 = new Foo { ID = 3, Name = "Foo3" };
        Foo foo5 = new Foo { ID = 5, Name = "Foo5" };
        Bar bar1 = new Bar { ID = 1, Name = "Bar1" };
        Bar bar2 = new Bar { ID = 2, Name = "Bar2" };
        Bar bar4 = new Bar { ID = 4, Name = "Bar4" };

        ObservableCollection<FooBarViewModel> fooBar = new ObservableCollection<FooBarViewModel>();
        fooBar.Add(new FooBarViewModel(foo1, bar1));
        fooBar.Add(new FooBarViewModel(bar2));
        fooBar.Add(new FooBarViewModel(foo3));
        fooBar.Add(new FooBarViewModel(bar4));
        fooBar.Add(new FooBarViewModel(foo5));

        this.DataContext = fooBar;
    }
}

public class Foo
{
    public int ID { get; set; }
    public string Name { get; set; }
}

public class Bar
{
    public int ID { get; set; }
    public string Name { get; set; }
}

public class FooBarViewModel : INotifyPropertyChanged
{
    public Foo WrappedFoo { get; private set; }
    public Bar WrappedBar { get; private set; }

    public int ID
    {
        get
        {
            if (WrappedFoo != null)
            { return WrappedFoo.ID; }
            else if (WrappedBar != null)
            { return WrappedBar.ID; }
            else
            { return -1; }
        }
        set
        {
            if (WrappedFoo != null)
            { WrappedFoo.ID = value; }
            if (WrappedBar != null)
            { WrappedBar.ID = value; }

            this.NotifyPropertyChanged("ID");
        }
    }

    public string BarName
    {
        get
        {
            return WrappedBar.Name;
        }
        set
        {
            WrappedBar.Name = value;
            this.NotifyPropertyChanged("BarName");
        }
    }

    public string FooName
    {
        get
        {
            return WrappedFoo.Name;
        }
        set
        {
            WrappedFoo.Name = value;
            this.NotifyPropertyChanged("FooName");
        }
    }

    public FooBarViewModel(Foo foo)
        : this(foo, null) { }
    public FooBarViewModel(Bar bar)
        : this(null, bar) { }
    public FooBarViewModel(Foo foo, Bar bar)
    {
        WrappedFoo = foo;
        WrappedBar = bar;
    }

    public event PropertyChangedEventHandler PropertyChanged;

    private void NotifyPropertyChanged(String info)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(info));
        }
    }
}

And then in the Window:

 <ListView ItemsSource="{Binding}">
    <ListView.View>
        <GridView>
            <GridViewColumn Header="ID" DisplayMemberBinding="{Binding ID}"/>
            <GridViewColumn Header="Foo Name" DisplayMemberBinding="{Binding FooName}"/>
            <GridViewColumn Header="Bar Name" DisplayMemberBinding="{Binding BarName}"/>
        </GridView>
    </ListView.View>
</ListView>
rmoore
Thanks rmoore. Unfortunately, the setup I have doesn't even respond to CollectionChanged events. I tried w/CompositeCollections, but since the collection I want to display isn't even of the same size as the two I input, I don't see how I'd make it work. Oddly, Convert method is only called once (per value), on initial display, and never again.
AdrianoFerrari
In that case, the easiest way to solve this without knowing more would be to create some sort of wrapper class that can merge a Target and/or Actual. Then if you create a single ObservableCollection of these wrappers, it should be much easier to bind to.
rmoore
I guess I'll have to do it that way. I'll post back here if I manage to do it the way I intended, since it would've been more straightforward.Thanks again rmoore. Is there anyway to award you points w/o marking this as answered?
AdrianoFerrari
Actually, that worked rather well, and wasn't as hard as I thought. If you'd like, you can write it as an answer rather than a comment, and I'll mark this as Answered.Thanks!
AdrianoFerrari
I added on an example as well, in case someone else stumbles upon this and doesn't initially follow.(Also, on the points: It's possible on questions, answers, and comments to mark them as helpful or unhelpful, here's some more info on it and how it works with points: http://stackoverflow.com/questions/130654/how-does-reputation-work-on-stackoverflow
rmoore