Billy Coover
Billy Coover

Reputation: 3837

How to Bind a WPF control to a WCF method using an ObjectDataProvider

I'm testing out WPF for the first time and I'm trying to call a WCF service with an ObjectDataProvider.

WCF Service named WcfService1 with a single method:

namespace WcfService1
{
    public class Service1 : IService1
    {

        public String HelloWorld()
        {
            return "Hello World!";
        }
    }
}

I added a Service Reference to my WPF project and named it TestService

In my main window, I can call this without issue in code behind. It seems simple; like a web service call:

TestService.Service1Client service = new TestService.Service1Client(); MessageBox.Show(service.HelloWorld());

I'm trying to create an ObjectDataProvider that points to this service. I guess I'm confused as to what the ObjectType should be? I've tried local, the service namespace, src; I'm lost:

<Window.Resource>
    <ObjectDataProvider 
        x:Key="odpTestService" 
        ObjectType="{x:Type **TestService**:Service1Client}" 
        MethodName="HelloWorld" />
</Window.Resources>

Ultimatly it will bind to a TextBlock:

<TextBlock Grid.Column="0" Grid.Row="0" 
Grid.ColumnSpan="2" Background="AliceBlue"
Text="{Binding Source={StaticResource odpTestService}}" />

I was trying to work from the Flickr example posted here: http://khason.net/blog/wpf-binding-to-wcf-and-more/

Update: The answer from Denis did solve part of the issue here. Now, I'm getting an error on compile: System.Windows.Data Error: 34 : ObjectDataProvider: Failure trying to invoke method on type;

The ObjectDataProvider can't invoke the HelloWorld method with type IService1 (Using the method and type from my example). Any ideas why?

Upvotes: 1

Views: 2491

Answers (1)

Denis Troller
Denis Troller

Reputation: 7501

You need to import the service's namespace through an xmlns directive at the top of the file:

Assuming that the reference has been added directly to your application, and that your application's root namespace is "MyApplication":

<Window x:class="MyApplication.MyWindow"
        xmlns:srv="MyApplication.TestService">

        <Window.Resource>
            <ObjectDataProvider 
                x:Key="odpTestService" 
                ObjectType="{x:Type srv:Service1Client}" 
                MethodName="HelloWorld" />
        </Window.Resources>

        <TextBlock Grid.Column="0" Grid.Row="0" 
          Grid.ColumnSpan="2" Background="AliceBlue"
          Text="{Binding Source={StaticResource odpTestService}}" />

</Window>

Upvotes: 1

Related Questions