WPF中使用MVVM进行multibinding

时间:2020-03-26
本文章向大家介绍WPF中使用MVVM进行multibinding,主要包括WPF中使用MVVM进行multibinding使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

背景描述:在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();
        }
    }

原文地址:https://www.cnblogs.com/larissa-0464/p/12572363.html