带有绑定参数的MarkupExtension [英] MarkupExtension with binding parameters

查看:64
本文介绍了带有绑定参数的MarkupExtension的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在处理自定义MarkupExtension,其中我需要来自XAML的非字符串参数来构造新对象.可以在DataContext范围内的字段上使用非字符串参数绑定吗?

I am working on a custom MarkupExtension in which I need a non string parameters from XAML to construct the new object. Is it possible to use a non-string parameter binding on a field in DataContext scope?

换句话说,我该怎么做?

In other words, how can I do something like this?

<ListBox ItemsSource="{Binding Source={local:MyMarkupExtension {x:Type Button},IncludeMethods={Binding Source=CustomerObject.IsProblematic}}}" />

其中IncludeMethods=CustomerObject.IsProblematic给我这个错误:

不能在类型为'TypeDescriptorExtension'的'IncludeMethods'属性上设置绑定.只能在DependencyObject的DependencyProperty上设置绑定".

Binding cannot be set on the 'IncludeMethods' property of type 'TypeDescriptorExtension'. A 'Binding' can only be set on a DependencyProperty of a DependencyObject.

有人可以帮助我吗?

谢谢

推荐答案

只能在DependencyObject的DependencyProperty上设置'Binding'-这是事实.问题是MarkupExtension类不是从DependencyObject派生的,这就是为什么无法在其属性上设置绑定的原因.

A 'Binding' can only be set on a DependencyProperty of a DependencyObject - it is true. The problem is that MarkupExtension class does not derive from DependencyObject, that's why it is not possible to set binding on it's properties.

解决方法正在使用 ValueConverters .另一个解决方法是更改​​C#语言以允许多重继承.顺便说一句,在Silverlight中,MarkupExtension实现了IMarkupExtension接口,因此我尝试在自定义扩展中实现它,并从DependecyObject派生它,在其中添加DependencyProperty并对其设置绑定.它不会崩溃,但是实际上在 调用ProvideValue()之后设置了绑定.因此,即使在Silverlight中也没有解决方案(或者很难解决-请参阅 Klaus78的答案中提供的链接).在WPF中,MarkupExtension没有实现任何接口,因此您无法绑定到它的属性.

Workaround is using ValueConverters. Another workaround is to change C# language to allow multiple inheritance. By the way, in Silverlight MarkupExtension implements IMarkupExtension interface, so I tried to implement it in my custom extension and derive it from DependecyObject, added DependencyProperty there and set binding to it. It doesn't crash, but the binding is actually set after ProvideValue() is called. So even in Silverlight there's no solution (or it is difficult - see link provided in Klaus78's answer). In WPF MarkupExtension doesn't implement any interface, so you cannot bind to it's properties.

这篇关于带有绑定参数的MarkupExtension的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆