问题
How to bind multiple WPF TextBoxes holding numerical values to change the same absolute amount if one of the TextBox value is changed?
Lets say I have the above UI. If the CheckBox is not checked, I need the regular binding to ViewModel property (this is what I have now):
<TextBox Text="{Binding Value1}" />
<TextBox Text="{Binding Value2}" />
<TextBox Text="{Binding Value3}" />
<TextBox Text="{Binding Value4}" />
<TextBox Text="{Binding Value5}" />
<CheckBox Content="Relative Changes Constant" IsChecked="{Binding UseRelative}" />
If the CheckBox is checked however and the value in any TextBox is changed, I need to have all other TextBox values updated the same relative amount up or down. For example, if the 2nd TextBox value is updated from 25 -> 30. The other 4 TextBox values should then become 39, 26, 30 and 32 (increase by 5).
回答1:
Here's a solution that uses just two properties...
private int _value1;
public int Value1
{
[DebuggerStepThrough]
get { return _value1; }
[DebuggerStepThrough]
set
{
if (value != _value1)
{
if (UseRelative)
{
UpdateRelative(value - _value1);
}
else
{
_value1 = value;
OnPropertyChanged("Value1");
}
}
}
}
private int _value2;
public int Value2
{
[DebuggerStepThrough]
get { return _value2; }
[DebuggerStepThrough]
set
{
if (value != _value2)
{
if (UseRelative)
{
UpdateRelative(value - _value2)
}
else
{
_value2 = value;
OnPropertyChanged("Value2");
}
}
}
}
private void UpdateRelative(int increment)
{
_value1 += increment;
_value2 += increment;
// update the view
OnPropertyChanged("Value1");
OnPropertyChanged("Value2");
}
In this example, there is an intervention in the setter just before the backing field is set which queries if the UseRelative value is true. If it is, the setter calls the UpdateRelative method and returns.
The UpdateRelative method operates on the backing fields and once the calculations are performed, it calls OnPropertyChanged on the public fields. The WPF binding engine will then query the getters and update the view (because the getters use the backing fields).
When UseRelative is false, it's business as usual: i.e., the standard WPF property model. The two properties in this sample can be extended to include the 5 in your question using the same technique.
来源:https://stackoverflow.com/questions/18195870/wpf-bind-numeric-values-in-textboxes-to-change-relative-to-each-other