绑定的默认 ValueConverter
有没有办法让 WPF 自动将 Converter
应用到特定类型的所有绑定?
我见过这个问题,但它涵盖了不同的情况(本地化),因此没有令人满意的答案。
我的问题:我有包含 Commands
的模型类,我想将其绑定到 WPF 命令。 由于模型类独立于工具包,因此我无法在那里实现 WPF 的 ICommand
。 相反,我有一个 CommandConverter
,它将 CommandModel
包装到 WPF ICommand
中:
<Button Command="{Binding MyCommand, Converter={StaticResource CommandConverter}}" />
这工作得很好,除了很容易忘记 < code>Converter= 并且 WPF 没有给出任何绑定失败的指示。
我现在的问题是:是否有可能强制 WPF 始终将转换器应用于特定类型的绑定? 或者,当命令绑定失败时,如何让 WPF 给出正确的错误?
Is there a way to get WPF to automatically apply a Converter
to all bindings of a specific type?
I've seen this question, but it covers a different case (localisation) and thus has no satisfying answers.
My problem: I've got model classes containing Commands
, which I would like to bind to WPF Commands. Since the model classes are toolkit-independent, I cannot implement WPF's ICommand
there. Instead I have a CommandConverter
which wraps CommandModel
s into WPF ICommand
s:
<Button Command="{Binding MyCommand, Converter={StaticResource CommandConverter}}" />
This works quite well, except that it is easy to forget about the Converter=
and WPF doesn't give any indication that the binding failed.
My question is now: Is there a possibility to force WPF to always a apply a converter to specific types of bindings? Or, alternatively, how can I get WPF to give me proper errors when a Command binding fails?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我认为如果没有对 Button 进行子类化(您可能不想这样做),或者定义自己的附加属性并在其上使用 TypeConverter 属性,您就无法实现。
如果您想通过新附加属性上的 TypeConverter 属性使用默认转换器,您可以查看 Rob Relyea 的信息帖子 此处,或 MSDN 此处。
I don't think you can without either sub-classing Button (you probably don't want to do this), or defining your own attached property and using a TypeConverter attribute on it.
If you want to go with using a default converter via the TypeConverter attribute on a new attached property, you can look at Rob Relyea's informative post here, or MSDN here.
虽然我从未这样做过,但是否可以定义自定义标记扩展? 这应该会导致该值被发送到实现标记扩展的类,然后您可以从那里返回
Command
属性所期望的ICommand
。正如我所说,我从来没有自己创建过一个,而是 Google搜索似乎会带来一些关于如何做到这一点的文章。
While I've never done it, would it be possible to define a custom Markup Extension? That should cause the value to be sent to your class that implements the Markup Extension, and then from there you can return an
ICommand
that theCommand
property is expecting.As I said, I've never created one my self, but a Google Search seems to bring up a few articles on how to do it.
检查调试输出窗口。 通常您会看到那里的绑定错误。
Check the debug output window. Normally you get to see the binding errors there.