Bind to a collection's view and just call ToString() in WPF

落爺英雄遲暮 提交于 2019-12-12 15:35:43

问题


I'm binding a GridView to a collection of objects that look like this:

public class Transaction
{
   public string PersonName { get; set; }
   public DateTime TransactionDate { get; set; }
   public MoneyCollection TransactedMoney { get; set;}
}

MoneyCollection simply inherits from ObservableCollection<T>, and is a collection of MyMoney type object.

In my GridView, I just want to bind a column to the MoneyCollection's ToString() method. However, binding it directly to the TransactedMoney property makes every entry display the text "(Collection)", and the ToString() method is never called.

Note that I do not want to bind to the items in MoneyCollection, I want to bind directly to the property itself and just call ToString() on it.

I understand that it is binding to the collection's default view. So my question is - how can I make it bind to the collection in such a way that it calls the ToString() method on it?

This is my first WPF project, so I know this might be a bit noobish, but pointers would be very welcome.


回答1:


Write a IValueConverter implementation that calls ToString() on the bound collection and returns it and use this converter in the XAML binding expression.




回答2:


You can add property StringRepresentation or something like this in MyMoney class. If you do not want to affect this class, you should write a wrapper - MyMoneyViewModel which will have all needed properties. This is a common way. HIH!



来源:https://stackoverflow.com/questions/2925768/bind-to-a-collections-view-and-just-call-tostring-in-wpf

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!