我在XAML中以Text
的{{1}}属性设置绑定:
TextBlock
我想从当前使用的代码隐藏依赖项中更改转换器。如何从代码中获取和设置绑定的转换器?我喜欢像:
<TextBlock x:Name="MyTextBlock" TextWrapping="Wrap" Text="{Binding TextProperty, Converter={StaticResource MyConverter}}"/>
答案 0 :(得分:4)
您需要自行获取绑定:
//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;
}
}
*/
}