代码之家  ›  专栏  ›  技术社区  ›  Billy Coover

如何使用ObjectDataProvider将WPF控件绑定到WCF方法

  •  1
  • Billy Coover  · 技术社区  · 16 年前

    我第一次测试了wpf,并尝试使用ObjectDataProvider调用wcf服务。

    具有单个方法的名为wcfservice1的wcf服务:

    namespace WcfService1
    {
        public class Service1 : IService1
        {
    
            public String HelloWorld()
            {
                return "Hello World!";
            }
        }
    }
    

    我向我的WPF项目添加了一个服务引用,并将其命名为testservice。

    在我的主窗口中,我可以在代码隐藏中无问题地调用它。这看起来很简单;就像一个Web服务调用:

    testservice.service1Client service=new testservice.service1Client(); messagebox.show(service.helloworld());

    我正在尝试创建一个指向此服务的ObjectDataProvider。我想我对对象类型应该是什么很困惑?我尝试过本地服务名称空间SRC;我迷路了:

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

    最后它将绑定到一个文本块:

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

    我试着从这里发布的Flickr示例开始工作: http://khason.net/blog/wpf-binding-to-wcf-and-more/

    更新: 丹尼斯的回答确实解决了部分问题。现在,我在编译时出错: System.Windows.Data错误:34:ObjectDataProvider:尝试对类型调用方法失败;

    ObjectDataProvider无法调用类型为IService1的HelloWorld方法(使用我的示例中的方法和类型)。你知道为什么吗?

    1 回复  |  直到 13 年前
        1
  •  1
  •   Denis Troller    16 年前

    您需要通过文件顶部的xmlns指令导入服务的命名空间:

    假设引用已直接添加到应用程序中,并且应用程序的根命名空间为“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>