天天看點

WPF中使用MVVM進行multibinding

背景描述:在Number1和Number2文本框中輸入數字後,在Answer文本框中會按照下圖所示顯示。

WPF中使用MVVM進行multibinding
 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();
        }
    }      
WPF

繼續閱讀