WPF 多值转换器

和普通转换器原理差不多

先看效果 最后一行的值是前面的总和

技术图片

 

首先创建一个类继承接口 IMultiValueConverter 

class NumMultiConvert : IMultiValueConverter { #region Field 字段 #endregion #region Constructor 构造函数 #endregion #region Property 属性 #endregion #region Event 事件 #endregion #region Method 方法 #endregion public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture) { return values.Where(i => i != null).Select(i => System.Convert.ToDouble(i)).Sum().ToString(); } public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture) { throw new NotImplementedException(); } }

前台引用转换器

<Window.Resources>
<local:NumMultiConvert x:Key="NumMultiConvert" />
</Window.Resources>

使用

<StackPanel Orientation="Vertical"> <TextBox Name="tb1" Width="100" FontSize="30" Text="25" /> <TextBox Name="tb2" Width="100" FontSize="30" Text="75" /> <TextBox Name="tb3" Width="100" FontSize="30" Text="55" /> <TextBox Name="tb4" Width="100" FontSize="30" Text="10" /> <TextBlock Width="100" FontSize="30"> <TextBlock.Text> <MultiBinding Converter="{StaticResource NumMultiConvert}"> <Binding ElementName="tb1" Path="Text" /> <Binding ElementName="tb2" Path="Text" /> <Binding ElementName="tb3" Path="Text" /> <Binding ElementName="tb4" Path="Text" /> </MultiBinding> </TextBlock.Text> </TextBlock> </StackPanel>

 

注意 MultiBinding 在XAML里面没有智能提示。。。。

 

相关文章