2013-08-29 60 views
1

我有两个文本框:用户输入的最小和最大值。如果最大号码小于最小号码,则最大文本框中的号码将自动更改为与最小号码文本框中的最小号码相同的号码。最小和最大绑定

用wpf和C#实现它的最好方法是什么?代码会很棒。

谢谢!

回答

0

在您的ViewModel中定义两个int类型的MinValue和MaxValue(如果使用MVVM)并绑定到两个文本框。

C#

private int minValue; 
    private int maxValue; 

    public int MinValue 
    { 
     get { return minValue; } 
     set 
     { 
      minValue = value; 
      PropertyChanged(this, new PropertyChangedEventArgs("MinValue")); 

      if (minValue > maxValue) 
      { 
       MaxValue = minValue; 
      } 
     } 
    } 


    public int MaxValue 
    { 
     get { return maxValue; } 
     set 
     { 
      maxValue = value; 
      PropertyChanged(this, new PropertyChangedEventArgs("MaxValue")); 
      if(maxValue < minValue) 
      { 
       MinValue = maxValue; 
      } 
     } 
    } 

的XAML:

<TextBox Text="{Binding MinValue, UpdateSourceTrigger=PropertyChanged}"/> 
<TextBox Text="{Binding MaxValue, UpdateSourceTrigger=PropertyChanged}"/> 

感谢

+0

非常感谢。有效。我只需切换minValue = maxValue。 –

+1

很高兴它的工作。你可能想接受答案;) – Nitin

0

只是把我在MIN数值我的WPF代码实现的方式是0和MAX的数值为99。 希望这可以帮助

<!-- WPF Code Sample.xaml --> 
<TextBox 
    Text="1" 
    Width="20" 
    PreviewTextInput="PreviewTextInputHandler" 
    IsEnabled="True"/> 

https://social.msdn.microsoft.com/Forums/vstudio/en-US/990c635a-c14e-4614-b7e6-65471b0e0e26/how-to-set-minvalue-and-max-value-for-a-testbox-in-wpf?forum=wpf

// C# Code Sample.xaml.cs    
private void PreviewTextInputHandler(object sender, TextCompositionEventArgs e) 
{ 
    // MIN Value is 0 and MAX value is 99 
    var textBox = sender as TextBox; 
    bool bFlag = false; 
    if (!string.IsNullOrWhiteSpace(e.Text) && !string.IsNullOrWhiteSpace(textBox.Text)) 
    { 
     string str = textBox.Text + e.Text; 
     bFlag = str.Length <= 2 ? false : true; 
    } 
    e.Handled = (Regex.IsMatch(e.Text, "[^0-9]+") || bFlag); 
}