Problem with WPF data binding to F# interface

Problem with WPF data binding to F# interface

I've defined a simple interface in F# and generated an instance of it using an object expression. When I try to databind to that instance from WPF it isn't working at all. When I set up the databinding expressions the WPF designer won't let me browse the interface members. Instead it shows the interface object as being of type NewFood @ 11 rather than as type IFood. Weird. However I have no trouble at all browsing and pulling out the property values of IFood in my C# code directly and can databind to those extracted properties. Why can't I bind to the exported F# interface directly? 

type public IFood =
    abstract member Fruit : string
    abstract member Vegetable : string

module private Utility =
    let newFood =
        { new IFood with
            member this.Fruit = "orange"
            member this.Vegetable = "carrot"
        }

[<AbstractClass; Sealed>]
type public Food =
    static member NewFood = Utility.newFood


    public class MainWindowViewModel
    {
        IFood food = Calculator.Food.NewFood;

        public IFood Food { get { return food; } }
        public string Fruit { get { return food.Fruit; } }
        public string Vegetable { get { return food.Vegetable; } }
    }

Here is someone having a similar problem but I don't understand the comments about what is happening.

I'm not a WPF expert, but perhaps something along the lines of this StackOverflow answer would work for you?

As to why this happens, it's because in F# all interface implementations are explicit, meaning that the methods that implement the interface are private to the implementing type, rather than public.  Thus, one other workaround might be to use an abstract class (whose methods will be public) instead of an interface (as long as there's no other base class that you need to derive from).

Copyright © 2007-2012 www.chuibin.com Chuibin Copyright