WPF DataGrid - 结合TimeSeries w / MultiBinding,丢失更改通知。为什么? [英] WPF DataGrid - Combining TimeSeries w/MultiBinding, lose change-notification. Why?

查看:270
本文介绍了WPF DataGrid - 结合TimeSeries w / MultiBinding,丢失更改通知。为什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类有两个ObservableCollection< TimeValue>,其中TimeValue是与更改通知(通过INotifyPropertyChanged)进行自定义的DateTime / Value配对。我称之为这些目标和实际。



当我将这些绑定到图表时,一切都很好,我得到两个LineSeries。如果我将其中一个绑定到一个DataGrid,其中列为Date,列为Value,则再次工作。我甚至得到了我需要的TwoWay绑定。



但是,我需要一个DataGrid,它具有一个Date列,每个列为Targets和Actuals。问题是我需要列出一个范围内的所有日期,而其中某些日期在目标,实际或两者中可能没有相应的值。



所以,我决定我会做一个MultiBinding,它将Targets和Actuals作为输入,并输出一个组合的TimeSeriesC,每当任何一个原始文件没有值时,该值将为空值。



但是对基础数据的任何更改都没有回应。



这个工作正常(绑定到一个ObservableCollection):

 < ctrls:DataGrid Grid.Row =1Height =400AutoGenerateColumns =FalseCanUserDeleteRows =FalseSelectionUnit =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 =DateBinding ={Binding Date,StringFormat = {} {0:ddd,MMM d}}/>
< ctrls:DataGridTextColumn Header =TargetBinding ={Binding Value}/>
<! - < ctrls:DataGridTextColumn Header =TargetBinding ={Binding Value [0]}/>
< ctrls:DataGridTextColumn Header =ActualBinding ={Binding Value [1]}/> - >
< / ctrls:DataGrid.Columns>



首先初始化没有响应更改通知:

 < ctrls:DataGrid Grid.Row =1Height =400AutoGenerateColumns = FalseCanUserDeleteRows =FalseSelectionUnit =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 =DateBinding ={Binding Date,StringFormat = {} {0:ddd,MMM d}}/>
<! - < ctrls:DataGridTextColumn Header =TargetBinding ={Binding Value}/> - >
< ctrls:DataGridTextColumn Header =TargetBinding ={Binding Value [0]}/>
< ctrls:DataGridTextColumn Header =ActualBinding ={Binding Value [1]}/>
< / ctrls:DataGrid.Columns>



这里是我的IMultiValueConverter:

  class TargetActualListConverter:IMultiValueConverter 
{
public object Convert(object [] values,Type targetType,object参数,System.Globalization.CultureInfo文化)
{
TimeSeries< double> Targets =值[0]作为TimeSeries< double>;
TimeSeries< double> Actuals =值[1]作为TimeSeries< double>;
DateTime [] range = TimeSeries< double> .GetDateRange(Targets,Actuals); //获取最小和最大日期
int count =(range [1] - range [0])。Days; / /总天数
DateTime currDate = new DateTime();
TimeSeries< double?[]> combined = new TimeSeries< double?[]>(); (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));
}
返回组合;
}

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

foreach(TimeValue< double?[]>电视合并)
{
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};
返回结果;

}
}

我不能太过分关闭,因为它显示的值。



我做错了什么?
或者,还有一个更简单的方法呢?



感谢所有!

解决方案

看起来这是由转换器引起的。 ObservableCollection实现INotifyCollectionChanged,它会在对集合进行更改(Add / Remove / Replace / Move / Reset)时通知UI。这些都是对集合的更改,而不是集合的内容,因此您之前看到的更新是由于您的类实施INotifyPropertyChanged。因为MultiCoverter正在返回一个新的对象集合,所以初始集合中的数据不会传播到这些对象,因为没有绑定原始对象以供他们通知。



我建议的第一件事是看看 CompositeCollection 元素,看看是否符合您的需求。



而不是像您一样设置ItemsSource,您可以保留原始对象像:

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

(我假设没有回应底层数据的任何更改是指更改价值观,不修改收藏,如果我不正确让我知道,我会深入了解一下。)



编辑添加 $
如果这不行,替代方法是编写一个新的类,将包含Target和Actual集合。然后可以使用这些包装器创建一个ObservableCollection。这实际上是使用ValueConverter或使用CompositeCollection更好的方法。无论您是否松动了最初存在的一些功能。通过使用值转换器重新创建集合,它不再直接绑定到原始对象,因此属性通知可能会丢失。通过使用CompositeCollection,您不再具有可以通过add / delete / move等进行迭代或修改的单个集合,因为它必须知道要操作哪个集合。



这种类型的包装功能在WPF中非常有用,而且是一个非常简化的版本的ViewModel,这是MV-VM设计模式的一部分。当您无法访问基础类以添加INotifyPropertyChanged或IDataErrorInfo时,可以使用它,还可以帮助添加其他功能,例如状态和交互到底层模型。



下面是一个简短的示例,演示了这两个初始类具有相同Name属性的功能,并且不实现它们之间未共享的INotifyPropertyChanged。

  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;组; }
public string Name {get;组; }
}

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

public class FooBarViewModel:INotifyPropertyChanged
{
public Foo WrappedFoo {get;私人集合}
public Bar WrappedBar {get;私人集合}

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) ;
}
}
}

然后在窗口中:

 < ListView ItemsSource ={Binding}> 
< ListView.View>
< GridView>
< GridViewColumn Header =IDDisplayMemberBinding ={Binding ID}/>
< GridViewColumn Header =Foo NameDisplayMemberBinding ={Binding FooName}/>
< GridViewColumn Header =条名称DisplayMemberBinding ={Binding BarName}/>
< / GridView>
< /ListView.View>
< / ListView>


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!

解决方案

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>

这篇关于WPF DataGrid - 结合TimeSeries w / MultiBinding,丢失更改通知。为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆