绑定到的DataContext方法 [英] Binding to a method in DataContext

查看:192
本文介绍了绑定到的DataContext方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有可能使用的DataContext的方法在绑定?

Is it possible to use a method of the DataContext in a binding?

例如。签名公共BOOL ProjectIsActive(INT数) [注:不是静态],它可以在绑定声明

E.g. the signature public bool ProjectIsActive(int number) [note: not static], can it be declared in a binding?

编辑:继YWM和谢里登我试图将资源添加到我的窗口名称为_this的建议结果
我改了签名,以公共BOOL ProjectIsActive(目标数)

Following the suggestion of ywm and Sheridan I tried adding a resource to my Window with name _this.
I changed the signature to public bool ProjectIsActive(object number).

<Window.Resources>
<ObjectDataProvider x:Key="ProjectIsActive"
                    ObjectInstance="_this.DataContext"
                    MethodName="ProjectIsActive">
    <ObjectDataProvider.MethodParameters>
        <sys:Object></sys:Object>
    </ObjectDataProvider.MethodParameters>
</ObjectDataProvider>
</Window.Resources>

然后绑定触发的设置为:

Then the Binding of the Trigger is set as:

<Binding  Source="{StaticResource ProjectIsActive}" Path="MethodParameters[0]" BindsDirectlyToSource="true" />

它给人的错误:
System.Windows.Data错误:35:ObjectDataProvider的:失败尝试调用方法的类型;方法='ProjectIsActive'; TYPE =字符串;错误='没有方法相匹配的参数签名中。 MissingMethodException:system.missingMethodException而:方法System.String.ProjectIsActive找不到。
   在System.RuntimeType.InvokeMember(字符串名称,的BindingFlags的BindingFlags,活页夹粘结剂,目标对象,对象[] providedArgs,ParameterModifier []修饰符,CultureInfo的文化的String [] namedParams)
   在System.Windows.Data.ObjectDataProvider.InvokeMethodOnInstance(例外急症)

ObjectDataProvider.MethodParameters的方法签名不从输入放慢参数distinghuish返回值,我不知道如何着手。

The method signature of ObjectDataProvider.MethodParameters doesn't distinghuish return value from input paramter, I don't know how to proceed.

请注意:我们的目标可以通过使用MultiValueConverter和转换法等我只是好奇,因为绑定到一个属性是那么容易铸造,并结合的方法[在我的案例]那么难来达到的。依然还有更好的方法来避免到一个方法的调用。

NOTE: The objective can be also achieved by using a MultiValueConverter and casting in the Convert method etc. I was only curious because binding to a property is so easy, and binding to a method [in my case] so difficult. There are also still better ways to avoid a call to a method.

推荐答案

您可以使用的 ObjectDataProvider的访问数据从一个方法返回。

You can use the ObjectDataProvider to access data returned from a method.

<Window.Resources>
  <ObjectDataProvider x:Key="colors"
  ObjectType="{x:Type local:ColorHelper}"
  MethodName="GetColorNames"/>
</Window.Resources>

这篇关于绑定到的DataContext方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆