【问题标题】:Get and set binding converter in code behind在后面的代码中获取和设置绑定转换器
【发布时间】:2012-09-10 16:31:12
【问题描述】:

我以这种方式在我的 XAML 中为TextBlockText 属性设置了绑定:

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

我想从当前使用的代码隐藏中更改转换器。如何从后面的代码中获取和设置绑定的转换器?我喜欢这样的东西:

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

【问题讨论】:

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


    【解决方案1】:

    您需要自己获取绑定:

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

    【讨论】:

    • BindingOperations 没有GetBindingBase 方法,它只显示SetBinding。它说'System.Windows.Data.BindingOperations' does not contain a definition for 'GetBindingBase'
    • 哦,Silverlight...我会更新的。 Silverlight 是二等公民,不像 WPF 那样受支持。我会避免它。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-10-29
    • 1970-01-01
    • 2016-05-16
    • 1970-01-01
    • 1970-01-01
    • 2023-03-21
    • 2014-09-02
    相关资源
    最近更新 更多