在后面的代码中获取并设置绑定转换器

and*_*ubi 2 c# silverlight xaml windows-phone-7 windows-phone-8

我通过以下方式在XAML 中将绑定设置为的Text属性TextBlock

<TextBlock x:Name="MyTextBlock" TextWrapping="Wrap" Text="{Binding TextProperty, Converter={StaticResource MyConverter}}"/>
Run Code Online (Sandbox Code Playgroud)

我想从当前使用的依赖代码背后的代码中更改转换器。如何从后面的代码获取并设置绑定的转换器?Id就像这样:

if (converter = x)
    converter = y;
else
    converter = x;
Run Code Online (Sandbox Code Playgroud)

use*_*116 5

您需要获取绑定本身:

//For WPF:
// var binding = BindingOperations.GetBindingBase(
//     MyTextBlock,
//     TextBlock.TextProperty);

//For SilverLight we have to use the expression:
var expr = MyTextBlock.GetBindingExpression(TextBlock.TextProperty);
if (expr != null)
{
    // for Silverlight we have to use the ParentBinding of the expression
    var binding = expr.ParentBinding;
    binding.Converter = yourLogicHere;

    // in WPF there are 3 types of bindings
    /*
    else if (binding is MultiBinding)
    {
        ((MultiBinding)binding).Converter = yourMultiLogicHere;
    }
    else if (binding is PriorityBinding)
    {
        foreach (var childBinding in ((PriorityBinding)binding).Bindings)
        {
            ((Binding)childBinding).Converter = yourLogicHere;
        }
    }
    */
}
Run Code Online (Sandbox Code Playgroud)