I have a list of 'tickets' which all derive from the abstract class TicketBase
.
public abstract class TicketBase
{
public DateTime PublishedTime { get; set; }
public String TicketType { get; set; }
}
public class TicketA : TicketBase
{
public string PropertyA { get; set; }
}
public class TicketB : TicketBase
{
public string PropertyB { get; set; }
}
In my main view model I query a database and get back a List<TicketBase> Tickets
, ordered in ascending order of PublishedTime.
In my view I want to have something like:
Property A: <most recent value of PropertyA>
Property B: <most recent value of PropertyB>
So I was thinking to have a SummaryViewModel
which I can bind to that has properties like:
public 开发者_StackOverflowstring LatestPropertyA { get; set; }
public string LatestPropertyB { get; set; }
and in the setters of these properties, simply do a linq query on the Tickets
collection which gets the top most ticket where TicketType is the relevant type and gets the appropriate property.
Is there a way I can pass in the TicketType as part of the binding or do I need to hardcode the type in each of the setter methods?
Also, is this the best approach to this way of binding, is there a better way using some feature of WPF bindings Im not familiar with?
Your base class should not be dependent on any children deriving from it so remove TicketType and use the is operator to figure out exact type of a TicketBase instance. Load your tickets into Tickets collection and access them from the view using regular data binding defined in XAML. Below sample code shows you how to write properties that uses linq.
An alternative would be to use value converters and data bind to Tickets. You pass the type and property name as parameters and in the value converter you return correct property value using reflection.
public class VM
{
public VM()
{
Tickets = DB.LoadTicketsSorted();
}
public string LatestPropertyA { get { return Tickets.Where(t => t is TicketA).Select(t => (t as TicketA).PropertyA).FirstOrDefault(); } }
public string LatestPropertyB { get { return Tickets.Where(t => t is TicketB).Select(t => (t as TicketB).PropertyB).FirstOrDefault(); } }
private List<TicketBase> Tickets;
}
精彩评论