我在 XAML 中以这种方式将绑定(bind)设置为 TextBlock
的 Text
属性:
<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/