c# - 在后面的代码中获取和设置绑定(bind)转换器

标签 c# silverlight xaml windows-phone-7 windows-phone-8

我在 XAML 中以这种方式将绑定(bind)设置为 TextBlockText 属性:

<TextBlock x:Name="MyTextBlock" TextWrapping="Wrap" Text="{Binding TextProperty, Converter={StaticResource MyConverter}}"/>

我想根据当前使用的代码隐藏来更改转换器。如何从代码后面获取和设置绑定(bind)的转换器?我想要这样的东西:

if (converter = x)
    converter = y;
else
    converter = x;

最佳答案

您需要获取绑定(bind)本身:

//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;
        }
    }
    */
}

关于c# - 在后面的代码中获取和设置绑定(bind)转换器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12355837/

相关文章:

c# - 从 C# 和 .NET 自动启动 java-web-start 应用程序,.WaitForExit();不按预期工作

c# - 将子组件添加到父面板?

c# - .NET Forms 身份验证在超时之前注销用户

silverlight - 如何从导航历史记录中删除页面?

wcf - Silverlight WCF 代理仅异步?

WPF触发器属性

c# - 提供字符串字段时如何正确实现 IWebPartField.Schema

silverlight - MVVM-具有导航和可混合性的主/详细方案

c# - 创建全局集合并从所有页面访问它 (C# Windows)

c# - 选项卡上的文本框 SelectAll 但不是鼠标单击