簡單新增轉換器 IMultiValueConverter
展示如何建立簡單的 IMultiValueConverter 轉換器並在 xaml 中使用 MultiBinding。獲取 values 陣列傳遞的所有值的總和。
public class AddConverter : IMultiValueConverter
{
    public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
    {
        decimal sum = 0M;
        foreach (string value in values)
        {
            decimal parseResult;
            if (decimal.TryParse(value, out parseResult))
            {
                sum += parseResult;
            }
        }
        return sum.ToString(culture);
    }
    public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
    {
        throw new NotSupportedException();
    }
}
使用轉換器
- 名稱空間
 
xmlns:converters="clr-namespace:MyProject.Converters;assembly=MyProject"
- 定義資源
 
<converters:AddConverter x:Key="AddConverter"/>
- 在繫結中使用它
 
<StackPanel Orientation="Vertical">
    <TextBox x:Name="TextBox" />
    <TextBox x:Name="TextBox1" />
    <TextBlock >
        <TextBlock.Text>
            <MultiBinding Converter="{StaticResource AddConverter}">
                <Binding Path="Text" ElementName="TextBox"/>
                <Binding Path="Text" ElementName="TextBox1"/>
            </MultiBinding>
         </TextBlock.Text>
    </TextBlock>
</StackPanel>