如何根据值和另一个的textchanged计算文本框值

时间:2014-12-26 08:49:02

标签: c# wpf binding

我的申请是WPF,我已经面对下面的问题,请告诉我方向以克服它。 我们假设我有3个文本框:

<TextBox Height="23" HorizontalAlignment="Left" Margin="10,10,0,0" Name="textBox1" VerticalAlignment="Top" Width="120" />
<TextBox Height="23" HorizontalAlignment="Left" Margin="10,10,0,0" Name="textBox2" VerticalAlignment="Top" Width="120" />
<TextBox Height="23" HorizontalAlignment="Left" Margin="10,10,0,0" Name="textBox3" VerticalAlignment="Top" Width="120" />

所有文本框都将显示数字字符串。 textBox1.Text在代码后面分配,textBox2.Text由用户输入分配,我想要的是在textBox2的textChanged上分配textBox3.Text:

textBox3.text = string.Format("{0:0.00}", double.Parse(textBox2.Text) - double.Parse(textBox1.Text));

请告诉我如何实现这一目标?

2 个答案:

答案 0 :(得分:1)

如果使用MVVM模式,可以轻松实现。

<强>视图模型

public string TextBox1Text
{
    get{return _text1;}
    set{_text1 = value; NotifyPropertyChanged("ComputedProperty")}
}

public string TextBox2Text
{
    get{return _text2;}
    set{_text2 = value; NotifyPropertyChanged("ComputedProperty")}
}

public string ComputedProperty
{
    get {return string.Format("{0:0.00}", double.Parse(TextBox2Text) - double.Parse(TextBox1Text));}
}

<强> XAML

<TextBox Text="{Binding TextBox2Text, Mode=TwoWay}" />
<TextBox Text="{Binding TextBox1Text, Mode=TwoWay}" />    
<TextBox Text="{Binding ComputedProperty}" />

答案 1 :(得分:1)

感谢HighCore上面的链接,我终于能够做到了。 在我的情况下textBox3.Text依赖于其他两个textBoxes,所以我需要的是MultiBinding和相应的转换器类,它实现了IMultiConverter接口。

<TextBox Height="23" HorizontalAlignment="Left" Margin="10,10,0,0" Name="textBox1" VerticalAlignment="Top" Width="120" />
<TextBox Height="23" HorizontalAlignment="Left" Margin="10,10,0,0" Name="textBox2" VerticalAlignment="Top" Width="120" />
<TextBox Height="23" HorizontalAlignment="Left" Margin="10,10,0,0" Name="textBox3" VerticalAlignment="Top" Width="120">
    <TextBox.Text>
          <MultiBinding Converter="{StaticResource changeConverter}">
              <Binding ElementName="textBox2" Path="Text"></Binding>
              <Binding ElementName="textBox3" Path="Text"></Binding>
          </MultiBinding>
    </TextBox.Text>
<TextBox/>

并且转换器类是

public class ChangeConverter: IMultiValueConverter
    {
        public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            try
            {
                double par1 = double.Parse(values[0].ToString());
                double par2 = double.Parse(values[1].ToString());
                double res = par2 - par1;
                return res.ToString();
            }
            catch (Exception)
            {
                return null;
            }
        }

        public object[] ConvertBack(object value, Type[] targetTypes,
               object parameter, System.Globalization.CultureInfo culture)
        {
            throw new NotSupportedException("Cannot convert back");
        }
    }

感谢所有帮助过的人!我希望这个答案将来会对其他人有所帮助。