当我使用多重绑定时,转换器无法收集
public partial class TestControl : UserControl
{
public TestClass TimeData{get;set;}
public TestControl ()
{
InitializeComponent();
}
}
public class TestClass
{
public int DelayTime { get; set; } = 80;
}
当我使用此代码时,textblock.Text 将是 80_80。
<Grid DataContext="{Binding TimeData, ElementName=userControl, Mode=OneWay}">
<TextBlock Grid.Row="1">
<TextBlock.Text>
<MultiBinding StringFormat="{}{0}_{1}">
<Binding Path="DelayTime"/>
<Binding Path="DelayTime"/>
</MultiBinding>
</TextBlock.Text>
</TextBlock>
</Grid>
但是当我添加转换器时,它不起作用 object[] 值为 0,0;
<Grid DataContext="{Binding TimeData, ElementName=userControl, Mode=OneWay}">
<TextBlock Grid.Row="1">
<TextBlock.Text>
<MultiBinding Converter="{StaticResource MultiflyConverter}">
<Binding Path="DelayTime"/>
<Binding Path="DelayTime"/>
</MultiBinding>
</TextBlock.Text>
</TextBlock>
</Grid>
public class MultiflyConverter : IMultiValueConverter
{
public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
{
var a = System.Convert.ToInt32(values[0]);
var b = System.Convert.ToInt32(values[1]);
return a * b;
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
我该如何修复它?
在没有看到完整代码的情况下,很难准确说出错误原因。
但我可以假设这是可能的,因为转换不正确。
要实现类似于 Binding 中类型转换的转换,需要使用 TypeConveter。
示例:
/// <summary>A converter that converts all values into Int32 numbers
/// and returns the result of their multiplication.</summary>
public class MultiflyConverter : IMultiValueConverter
{
private readonly Int32Converter converter = new Int32Converter();
public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
{
int result = 1;
foreach (var value in values)
{
if (value is not int num)
{
if (converter.IsValid(value))
{
num = (int)converter.ConvertFrom(value)!;
}
else
{
continue;
}
}
result *= num;
}
return result.ToString();
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}