如何将控件的属性设置为 xaml 中函数的地址?

发布于 2024-08-26 01:34:04 字数 484 浏览 11 评论 0原文

我有一个具有“Filter”属性的控件,该属性需要一个定义如何过滤控件内容的函数。到目前为止,我在后面的代码中设置过滤器,如下所示:

MyControl.Filter = AddressOf Filters.MyFilter

在此示例中,MyFilter 是 Filters 类中的共享函数,具有以下签名:

公共共享函数 MyFilter(ByVal obj As Object, ByVal text As String) As Boolean

我想在 xaml 中设置它。我正在考虑将 Filters.MyFilter 设置为静态资源并这样设置:

...Filter="{StaticResource myFilter}"/>

但我无法将 Filters.MyFilter 设置为静态资源。关于如何实现这一目标有什么想法吗?

谢谢,

I have a control that has a "Filter" property that expects a function that defines how the contents of the control should be filtered. so far i am setting the filter in code behind as such:


MyControl.Filter = AddressOf Filters.MyFilter

In this example MyFilter is a shared function in the Filters class with the following signature:


Public Shared Function MyFilter(ByVal obj As Object, ByVal text As String) As Boolean

I would like to set this in xaml. I was thinking of setting the Filters.MyFilter as a static resource and setting it that way:


...Filter="{StaticResource myFilter}"/>

but i cant set Filters.MyFilter as a static resource. Any ideas on how to achieve this?

Thanks,

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

稀香 2024-09-02 01:34:05

您不能直接执行此操作。除了作为事件处理程序之外,XAML 不提供引用函数的方法。

您可以通过创建一个具有谓词类型属性的对象来间接做到这一点:(

public class FilterOMatic
{
  public Predicate<int> FilterProc
  {
    get { return n => (n % 2) == 0; }
  }
}

请原谅 C# 主义——我不太熟悉用于返回函数的 VB 语法。我认为它类似于 Return AddressOf Filters.MyFilter 但我可能是错的。)

现在您可以将 FilterOMatic 实例化为资源,并通过与该资源的绑定引用其 FilterProc 属性:

<Window.Resources>
  <local:FilterOMatic x:Key="fom" />
</Window.Resources>

<MyObject Filter="{Binding FilterProc, Source={StaticResource fom}}" />

You cannot do this directly. XAML doesn't provide a way to refer to functions, other than as event handlers.

You can do it indirectly, by creating an object that has a property of predicate type:

public class FilterOMatic
{
  public Predicate<int> FilterProc
  {
    get { return n => (n % 2) == 0; }
  }
}

(Pardon the C#-ism -- I'm not too familiar with the VB syntax for returning functions. I think it would be something like Return AddressOf Filters.MyFilter but I may be wrong.)

Now you can instantiate the FilterOMatic as a resource and reference its FilterProc property via a binding to that resource:

<Window.Resources>
  <local:FilterOMatic x:Key="fom" />
</Window.Resources>

<MyObject Filter="{Binding FilterProc, Source={StaticResource fom}}" />
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文