F# / SIlverlight Binding to algebraic datatypes
-
01-10-2019 - |
Question
Given a data structure of:
type Candidate = SalesRep of SalesRep | Analyst of Analyst
type ScorableCandidate = {
candidate: Candidate ;
mutable comments: string ;
mutable score: int ;
}
and a data grid that wants to be able to display either of the candidates, is it possible to bind (using the WPF binding) to the ScorableCandidate?
<telerik:GridViewDataColumn Header="First Name" DataMemberBinding="{Binding candidate.fname}" IsFilterable="False" Width="100"/>
I am thinking not, as the binding syntax would bneed to be able to deconstruct the type - which I don't think is possible.
Thx
T
Solution
I believe that you shouldn't have any trouble accessing the candidate
field of the record type (because record fields appear as standard .NET properties).
Regarding the discriminated union - I like the suggestion to use custom type convertors as Juliet suggests. Another simpler option would be to expose the fname
field (which is shared by both SalesRep
and Analyst
if I understand your example correctly) as a property of the Candidate
type:
type Candidate =
| SalesRep of SalesRep
| Analyst of Analyst
member x.Name =
match x with
| SalesRep s -> s.fname
| Analyst a -> a.fname
Then you should be able to use standard WPF binding syntax for binding to properties.