【问题标题】:WPF static property binding not working on a list viewWPF 静态属性绑定在列表视图上不起作用
【发布时间】:2011-07-20 18:50:02
【问题描述】:

我目前正在将列表视图绑定到对象列表,并且一切正常。

只要我放入我的 Window 元素 DataContext="{Binding RelativeSource={RelativeSource Self}}",我就可以很好地绑定到 xaml 后面的代码

我的 ListView 看起来像这样,我的绑定列与 MyCollection 项目的属性的绑定正常工作。

<ListView ItemsSource="{Binding MyCollection}">

虽然我总是希望它说同样的话,但对于其中一个专栏。例如,此列将始终包含“Hello World”

以下代码给我一个绑定错误:

<GridViewColumn Header="I want all fields to be Hello World" DisplayMemberBinding="{Binding Source={x:Static Member=MyNamespace.MyStaticClass},Path=MyStaticStringField}" />

我得到错误:

错误 MC3050:找不到类型“MyNamespace”。请注意,类型名称区分大小写。

MyNamespace 是与窗口本身相同的命名空间,并且 MyStaticClass 是公共的

如果我改为尝试:

<GridViewColumn Header="I want all fields to be Hello World" DisplayMemberBinding="{Binding Source={x:Static Member=MyStaticClass},Path=MyStaticStringField}" />

我得到错误:

错误 MC3029:“MyStaticClass”成员无效,因为它没有限定类型名称。

奇怪的是,当我这样做时,它会起作用:

<GridViewColumn Header="This works" DisplayMemberBinding="{Binding Source={x:Static Member=SystemFonts.IconFontFamily}, Path=Source}" />

我尝试绑定的字段的代码:

namespace MyNamespace
{
    public static class MyStaticClass
    {
        public static string MyStaticStringField{ get; set; }

    }
}

【问题讨论】:

  • 能否贴出课程的相关代码?

标签: c# wpf data-binding binding


【解决方案1】:

您不能直接绑定到包含命名空间的类

在页面或窗口或用户控件声明中设置名称空间 xmlns:mynamespace="pathtoyournamespace"

并像这样在绑定中引用它:{x:Static mynamespace:MyStaticClass}, Path....

【讨论】:

  • 你必须在 XAML 中声明命名空间。
  • 我已经放入了我的窗口元素:xmlns:rm="clr-namespace:MyNamespace;assembly=MyAssembly",然后只在Source 上的类名前面加上rm:,但它给了我与第二个错误相同的错误:错误MC3029:“MyStaticClass”成员无效,因为它没有限定类型名称。
【解决方案2】:

我认为你必须包含命名空间

xmlns:local="clr-namespace:MyNamespace"

然后像这样使用它:

{x:Static Member=local:MyStaticClass}

【讨论】:

  • 我已经放入了我的窗口元素:xmlns:rm="clr-namespace:MyNamespace;assembly=MyAssembly" 然后在源上的类名前面加上 rm:,但它给了我与第二个错误相同的错误:error MC3029: 'MyStaticClass' member is not valid because it does not have aqualified type name.
【解决方案3】:

另外添加到其他答案x:static 应该绑定到静态类MEMBER,而不是类本身。

【讨论】:

  • 请建议正确的语法
  • Pavlo 编写了正确的语法,但您的静态类中应该有 MyStaticStringField 静态字段
【解决方案4】:

使用x:Static,您需要指定静态字段或属性(不仅仅是类)的路径。

<GridViewColumn Header="I want all fields to be Hello World" DisplayMemberBinding="{Binding Source={x:Static MyNamespace:MyStaticClass.MyStaticStringField}}" />

另请注意,命名空间与类名用冒号(不是点)分隔。

【讨论】:

  • 这给了我一个运行时抛出的解析异常。
  • @wpf,您是否阅读过 Pavlo 所写的内容或只是直接复制粘贴到您的代码中?还查看错误详细信息可能会有很大帮助。否则只会浪费我们的时间。
  • @wpf pro pls - 是的,注意到了。更新了我的答案。
  • 谢谢! &lt;GridViewColumn Header="This works" DisplayMemberBinding="{Binding Source={x:Static Member=SystemFonts.IconFontFamily}, Path=Source}" /&gt; 工作对我来说很奇怪,但不是我在它之前尝试的命名空间。你知道为什么吗?
  • 顺便说一句,如果其他人发现这个线程,您需要将命名空间定义在您的窗口中,而不是在成员之前放置实际的命名空间。
猜你喜欢
  • 2011-01-18
  • 2012-09-03
  • 2016-08-20
  • 1970-01-01
  • 2015-10-15
  • 1970-01-01
  • 2014-01-29
  • 2017-11-18
  • 1970-01-01
相关资源
最近更新 更多