如何将Textblock.Text绑定到列表Count或Sum方法?

时间:2014-01-13 15:36:34

标签: c# wpf binding

是否可以将TextBlock.Text绑定到ObservableCollection以获取Count()或Sum(x => x.price)?

     productList= new ObservableCollection<productClass>();
    <TextBlock Name="SumPrice" Text="{Binding productList.Sum(x=>x.price) ??}" />
    <TextBlock Name="CountProducts" Text="{Binding productList.Count() ??}" />

谢谢!

@EDIT:

视图模型:

     public class ParagonClass : INotifyPropertyChanged
        {
         (...) private objects(...)

//public objects start
            public int PdID
            {
                get
                {
                    return _pdID;
                }
                set
                {
                    _pdID = value;
                    NotifyPropertyChanged("PdID");
                }
            }

//public objects end (there is lot of objects, so I didn't copy them all)


       public event PropertyChangedEventHandler PropertyChanged;
        private void NotifyPropertyChanged(String propertyName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }
    }

myWindow.xaml

        <ListView Grid.Row="1" Name="productsLV" >
                    <ListView.Resources>
                        <BooleanToVisibilityConverter x:Key="Boolean2Visibility" />
                    </ListView.Resources>
                    <ListView.ItemTemplate>
                        <DataTemplate>
(...)

Listview将itemssource绑定到observablecollection,如:

myWindow.xaml.cs

                productsList = new ObservableCollection<ParagonClass>(); 
                productsLV.ItemsSource = productsList;

所以我的ObservableCollection在窗口中创建为public。为了在我的班级得到总和和数,我需要得到那个集合,但没有静态,我认为它是不可能的。

3 个答案:

答案 0 :(得分:1)

您可以在视图模型中创建一个返回它的int属性:

public int Sum { get { return productList.Sum(x => x.Price); } }

然后您的绑定可以是:

<TextBlock Name="SumPrice" Text="{Binding Sum}" />

您可以对count财产执行相同的操作。

答案 1 :(得分:1)

您不能在绑定表达式中使用Linq查询,因此您需要将sum作为属性公开。

Count已经是属性,因此您不需要Linq Count()方法。只需绑定到productList.Count

答案 2 :(得分:0)

我建议将它绑定到ViewModel中返回正确计数的属性

public int ProductCount
{
    get { return productList.Count(); }
}

然后你可以这样做,

<TextBlock Name="CountProducts" Text="{Binding ProductCount}" />

确保在productList更改时,您引发事件以通知视图需要更新ProductCount属性,

this.PropertyChanged(this, new PropertyChangedEventArgs("ProductCount"));