我有一个DataGrid
支持手动处理的ObservableCollection<T>
后面的代码。当我将新项目添加到支持列表或删除项目时,将更新Count
,但不会通知ItemsSource
,以便更新Price
的总和。我什至尝试BindingList<T>
,但即使是Count
停止更新!什么是黑客?ObservableCollection不反映摘要计算的变化
XAML:
<Label>
<Label.Content>
<TextBlock>
<TextBlock.Text>
<MultiBinding StringFormat="{}Count: {0}, Sum: {1}" NotifyOnTargetUpdated="True" NotifyOnSourceUpdated="True">
<Binding ElementName="datagrid" Path="ItemsSource.Count" UpdateSourceTrigger="PropertyChanged"/>
<Binding ElementName="datagrid" Path="ItemsSource" Converter="{StaticResource SumConverter}" UpdateSourceTrigger="PropertyChanged" />
</MultiBinding>
</TextBlock.Text>
</TextBlock>
</Label.Content>
</Label>
SumConverter:
[ValueConversion(typeof(ObservableCollection<DocView>), typeof(String))]
public class SumConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (value != null && value is ObservableCollection<DocView>)
{
ObservableCollection<DocView> items = (ObservableCollection<DocView>)value;
return items.Sum(x => x.Price);
}
else
return 0;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
后面的代码:
ObservableCollection<DocView> list = new ObservableCollection<DocView>();
datagrid.DataContext = list;
确保你的属性实现INotifyPropertyChanged – reggaeguitar