【问题标题】:Bind to result of static class' method绑定到静态类方法的结果
【发布时间】:2013-12-23 06:51:45
【问题描述】:

我有以下几点:

namespace Foo {
  public static class Bar {
    public static int Fubar() {
      return 100;
    }
  }
}

现在我在 xaml 中。我想用那个方法来设置我的矩形的高度。

<Rectangle Height="{Binding Source=???}">

【问题讨论】:

  • 当你想'绑定到静态类的方法'时,为什么你要把你的问题命名为'WPF绑定到静态类的属性'我>'?
  • 这个问题是问如何绑定到静态类方法,而链接问题是问如何绑定到静态类property。有区别

标签: wpf xaml data-binding


【解决方案1】:

你需要一个 ObjectDataProvider 来绑定一个方法。

示例(根据您的命名空间/类/方法调整):

<Window x:Class="SerialPortBinding.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:ports="clr-namespace:System.IO.Ports;assembly=System"
        Title="MainWindow" SizeToContent="WidthAndHeight">
    <Window.Resources>
        <ObjectDataProvider ObjectType="{x:Type ports:SerialPort}" 
            MethodName="GetPortNames" x:Key="portNames"/>
    </Window.Resources>
    <ComboBox ItemsSource="{Binding Source={StaticResource portNames}}"/>
</Window>

可能不需要顶部的 xmnls 的组装部分;如果 CodeSense 中没有出现,请忽略它。

【讨论】:

  • -1 这根本不是真的...用户确实不需要需要这样做...他们可以使用@AjS 显示的x:Static 表示法。
  • OP 绑定到静态属性,而不是方法。您的代码对此有何帮助?
  • +1 道歉@doerig,我没有注意到问题作者实际上想绑定到一个方法的输出,因为他们的标题被命名为 WPF 绑定到静态类的属性我>。我必须先编辑您的答案,然后才能删除我的反对票,所以我只重新格式化了一行。
  • @DanPuzey,请再看看这个......我认为由于这个愚蠢的标题问题,你犯了和我一样的错误。
  • @Sheridan/doerig:感谢您指出我的错误。确实,doerig 的回答是正确的(问题需要编辑!)。抱歉!
【解决方案2】:

试试这样的:-

{Binding Source={x:Static classnamespace:Bar}, Path=Fubar}

【讨论】:

  • "命名空间前缀'classnamespace'未定义"
  • 你应该在你的 xaml:-xmlns:mynamespace="clr-namespace:ApplicationName" 这里声明 ApplicationName 是命名空间的名字。 {Binding Source={x:Static mynamespace:Bar}, Path=Fubar}
猜你喜欢
  • 2020-02-27
  • 1970-01-01
  • 2011-10-15
  • 2014-09-10
  • 1970-01-01
  • 1970-01-01
  • 2011-08-23
  • 2021-11-29
  • 2020-10-31
相关资源
最近更新 更多