两种情况都已解决,请查看第一个答案评论以获取信息。
这段代码编译虽然在运行时出错。异常说:
A first chance exception of type 'System.Windows.Markup.XamlParseException' occurred in PresentationFramework.dll
.
当我尝试为 MultiBinding 中的第二个绑定设置源时,会发生解析异常。我已经尝试了很多方法并浏览了大约 20 篇文章,但我无法找出这里有什么问题。
我最好的猜测是它以某种方式连接到了错误的转换器返回类型。
而且,顺便说一句,当您将 TextBox 更改为 TextBlock 时,第一种情况有效。第二种情况仍然无效。
情况1
XAML:
<UserControl x:Class="Draft.MainControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:draft="clr-namespace:Draft"
xmlns:s="clr-namespace:System;assembly=mscorlib"
Height="350" Width="352">
<UserControl.Resources>
<s:String x:Key="str1">HELLO</s:String>
<s:String x:Key="str2">WORLD</s:String>
<draft:StringConverter x:Key="myStringConverter"/>
</UserControl.Resources>
<Grid>
<TextBox Name="tb1">
<TextBox.Text>
<MultiBinding Converter="{StaticResource myStringConverter}">
<Binding Source="{StaticResource str1}" />
<Binding Source="{StaticResource str2}" />
</MultiBinding>
</TextBox.Text>
</TextBox>
</Grid>
</UserControl>
代码背后:
public class StringConverter : IMultiValueConverter
{
public object Convert( object[] values, Type targetType, object parameter, CultureInfo culture )
{
return ( values[0].ToString() + values[1].ToString() );
}
public object[] ConvertBack( object values, Type[] targetType, object parameter, CultureInfo culture )
{
throw new NotImplementedException();
}
}
提前致谢!
案例2
同样问题的另一种情况:
<Grid> <TextBlock TextWrapping="WrapWithOverflow"> <TextBlock.Resources> <s:Int32 x:Key="defaultHeight">2</s:Int32> <s:Int32 x:Key="defaultNum">10</s:Int32> <draft:MultiplierConverter x:Key="myConverter"/> </TextBlock.Resources> <TextBlock.Text> aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa </TextBlock.Text> <TextBlock.Height> <MultiBinding Converter="{StaticResource myConverter}"> <Binding Source="{StaticResource defaultNum}" Mode="OneWay" /> <Binding Source="{StaticResource defaultHeight}" Mode="OneWay" /> </MultiBinding> </TextBlock.Height> </TextBlock> </Grid> </UserControl>
Code behind:
public class MultiplierConverter : IMultiValueConverter { public object Convert( object[] values, Type targetType, object parameter, CultureInfo culture ) { if ( values.Count() == 2 && values[0] != DependencyProperty.UnsetValue && values[1] != DependencyProperty.UnsetValue ) { var num = (Int32)values[0]; var height = (Int32)values[1]; return ( num * height ); } return 0; } public object[] ConvertBack( object values, Type[] targetType, object parameter, CultureInfo culture ) { throw new NotImplementedException(); } } }