0

我一直在尝试找到一种将转换器绑定到返回转换器的属性的方法。

我的代码看起来像这样。

我有一堂课。

public class ConverterFactory 
  {
    public IValueConverter AuthorizationToEnabledConverter
        {
            get
            {
                return converter......
            }
        }
  }

我有一个UserControl资源和一个按钮。

 <UserControl.Resources>
   <ResourceDictionary>
        <converter:ConverterFactory x:Key="ConverterFactory" b:IsDataSource="true"/>
        <ObjectDataProvider x:Key="AutCon"  ObjectInstance="{StaticResource ConverterFactory}"       
           MethodName="AuthorizationToEnabledConverter"/>
    </ResourceDictionary>
</UserControl.Resources>
<Button IsEnabled="{Binding "Value" ,Converter={StaticResource AutCon}}" >Change</Button>

我希望能够将我的转换器绑定到某个返回IValueConverter.

有没有办法做到这一点?

4

1 回答 1

0

怎么样:

Binding b = new Binding("AuthorizationToEnabledConverter") { Source = this.FindResource("ConverterFactory")};
this.SetBinding(YourProperty, b);

或通过 XAML:

YourProperty="{Binding Source={StaticResource ConverterFactory}, Path="AuthorizationToEnabledConverter"}"

编辑:您不能绑定绑定的Converter-property,因为它不是DependencyProperty. 另一种方法是创建一个MarkupExtension像这样的自定义:

[MarkupExtensionReturnType(typeof(IValueConverter))]
public class ConverterDispenser:MarkupExtension
{
    public IValueConverter MainConverter
    {
        get { return new TestConverter();}
    }

    public override object ProvideValue(IServiceProvider serviceProvider)
    {
        //with the help of serviceProvider you can get information about the surrounding elements and maybe decide depending on those information which converter to return.
        return MainConverter;
    }
}

如何使用它:

<TextBox Text="{Binding Path=Source, Converter={local:ConverterDispenser}}""></TextBox>

另一种选择是Binding通过派生来实现您自己的Binding,然后为您的转换器添加一个新的 DependencyProperty。现在,您为此属性创建了一个 ValueChangedCallback,并且每次更改时,您都设置了原始转换器。

于 2013-09-23T08:50:09.427 回答