背景描述:在Number1和Number2文本框中输入数字后,在Answer文本框中会按照下图所示显示。
xaml代码:
<Window.Resources> <local:MyValueConverter x:Key="MyValueConverter"/> </Window.Resources> <Grid> <StackPanel HorizontalAlignment="Center" VerticalAlignment="Center"> <Label Content="Number1:" FontSize="15"/> <TextBox Width="200" Name="text1" Height="30" BorderThickness="3"/> <Label Content="Number2:" FontSize="15" Margin="0,10,0,0"/> <TextBox Width="200" Name="text2" Height="30" BorderThickness="3" /> <Label Content="Answer:" FontSize="15" Margin="0,10,0,0"/> <TextBox Width="200" Height="30" BorderThickness="3"> <TextBox.Text> <MultiBinding Converter="{StaticResource MyValueConverter}"> <Binding ElementName="text1" Path="Text"/> <Binding ElementName="text2" Path="Text"/> </MultiBinding> </TextBox.Text> </TextBox> </StackPanel> </Grid>
MyValueConverter.cs代码:
public class MyValueConverter : IMultiValueConverter { public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture) { try { double num1 = System.Convert.ToDouble(values[0].ToString()); double num2 = System.Convert.ToDouble(values[1].ToString()); //这里定义你希望输出的格式 string result = num1 + " + " + num2 + " = " + (num1 + num2).ToString(); return result; }catch(Exception ex) { return null; } } public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture) { throw new NotImplementedException(); } }