目前我正在研究 WPF 数据绑定(bind),但遇到了一个我不明白的问题。所以我把问题贴在这里,也许你已经知道哪里出了问题。
起初:我在 Windows Vista 32 位下使用 Visual Studio 2008,问题也存在于 Windows 7 RC1 64 位中,安装了最新的更新/服务包,但 Vista 仍在运行 SP1。
问题来了: 我无法在继承的 Binding 类中设置 ValueConverter。
这是我的自定义绑定(bind)类:
public class MyBinding : Binding
{
public MyBinding() : base() { }
public MyBinding(string path) : base(path) { }
}
这个类应该和原来的 Binding 类完全一样,因为目前它没有实现任何自己的逻辑。我可以在 XAML 中使用此类,如下所示:
<TextBlock Text="{local:MyBinding SomeProperty}" />
local是实现MyBinding类的命名空间。
现在我不明白的第一件事来了。 VS2008 在其错误窗口中显示以下错误消息(原始消息是德语,因为我运行的是德语系统 - 我没有英文错误消息,所以我会尝试翻译)
Kein Konstruktor des MyBinding-Typs weist 1-Parameter auf.
(No constructor of type MyBinding takes 1 argument)
尽管此错误显示项目编译正常并且 MyBinding 类按预期工作。为什么 Visual Studio 找不到相应的构造函数(我想说,它已正确实现)?
如果我将 XAML 代码更改为这样,我可以阻止这些消息:
<TextBlock Text="{local:MyBinding Path=SomeProperty}" />
错误消息消失了,因为调用了 MyBinding 的默认构造函数,一切正常,ok...
现在我想为我的属性绑定(bind)设置一个 ValueConverter,XAML 如下所示:
<Window.Resources>
<local:MyValueConverter x:Key="converter" />
</Window.Resources>
[...]
<TextBlock Text="{local:MyBinding Path=SomeProperty, Converter={StaticResource converter}}" />
[...]
...,这里我在编译时遇到以下错误(德语原文,我想,我还找到了英文的原始消息):
Beim Analysieren einer Markup Extension wurde für den Typ "MS.Internal.Markup.MarkupExtensionParser+UnknownMarkupExtension" die unbekannte Eigenschaft "Converter" gefunden. Zeile X Position Y.
(Unknown property 'Converter' for type 'MS.Internal.Markup.MarkupExtensionParser+UnknownMarkupExtension' encountered while parsing a Markup Extension. Line x position Y)
现在我无法再编译了,因为 VS 找不到转换器属性(这是原始绑定(bind)类的公共(public)属性)。
我已经设法让 MyBinding 类与我指定的转换器一起运行,但只需要一点技巧: 我已将以下属性添加到 MyBinding 类:
public Type ConverterType
{
get { return Converter == null ? null : Converter.GetType(); }
set { Converter = value == null ? null : (IValueConverter)Activator.CreateInstance(value); }
}
... 并且 XAML 对此进行了更改:
<TextBlock Text="{local:MyBinding Path=SomeString, ConverterType=local:MyValueConverter}" />
现在我的项目编译并运行良好。事实上,我认为这是一个很好的解决方案,因为您不必将转换器指定为静态资源,而且绑定(bind)表达式对我来说看起来更清晰一些。但最终,这不是解决方案。
所以谁能告诉我我做错了什么?为什么我不能在我的自定义绑定(bind)类中设置 Converter 属性?
谢谢! 最好的祝福, 雷内
最佳答案
在使用标记扩展进行一些进一步测试后,这个问题一遍又一遍地出现在我面前,经过更多的谷歌搜索,我想我已经找到了一个确认,这是 Visual Studio 设计器中的一个错误。有兴趣的可以看看
http://www.hardcodet.net/2008/04/nested-markup-extension-bug
最好的问候, 雷内
关于c# - 自定义绑定(bind)类无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1018039/