简体   繁体   中英

Two textboxes which sum of values are complementary

I have two textboxes for decimal input. The sum of the values in the textboxes should be equal to a Form's property decimal value.

I tried to use two MultiBindings with a MultiValueConverter like this:

xaml:

    <TextBox x:Name="textBox1" ...>
        <TextBox.Text>
            <MultiBinding Converter="{StaticResource complementaryConverter}" Mode="OneWay">
                <Binding ElementName="textBox2" Path="Text" />
                <Binding Path="TotalValue" />

            </MultiBinding>
        </TextBox.Text>
    </TextBox>
    <TextBox x:Name="textBox2" ...>
        <TextBox.Text>
            <MultiBinding Converter="{StaticResource complementaryConverter}" Mode="OneWay">
                <Binding ElementName="textBox1" Path="Text" />
                <Binding Path="TotalValue" />
            </MultiBinding>
        </TextBox.Text>
    </TextBox>

where TotalValue is a Form's property, and the complementaryConverter converter is:

public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {

        decimal result = (decimal)values[1] - (decimal)values[0];
        return result.ToString();
    }

This doesn't work because I should set one of the textboxes to initially be equal to the total value, and the other one to zero. Ideally I would like to have the converter making the complementary sum and the values of the textboxes bound to two Form's decimal property. I tried a lot of possibilities but I've been stuck in this silly problem for a couple of days, so any help would be appreciable.

I think you've chosen the wrong approach by binding the TextBoxes directly to each other. Instead, you should expose two dependency properties on your viewmodel (or Form as you say), one for each box. You can bind to those in the XAML, and in the setters for those properties, include the logic for altering the value of the other.

Here's a rough draft for one of the properties:

    public static readonly DependencyProperty Text1Property =
        DependencyProperty.Register("Text1", typeof(decimal), typeof(Form), 
                                    new PropertyMetadata(default(decimal)));

    public decimal Text1
    {
        get { return (decimal)GetValue(Text1Property); }
        set
        {
            SetValue(Text1Property, value);
            SetValue(Text2Property, TotalValue - value);
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM