我有兩個文本框:用戶輸入的最小和最大值。如果最大號碼小於最小號碼,則最大文本框中的號碼將自動更改爲與最小號碼文本框中的最小號碼相同的號碼。最小和最大綁定
用wpf和C#實現它的最好方法是什麼?代碼會很棒。
謝謝!
我有兩個文本框:用戶輸入的最小和最大值。如果最大號碼小於最小號碼,則最大文本框中的號碼將自動更改爲與最小號碼文本框中的最小號碼相同的號碼。最小和最大綁定
用wpf和C#實現它的最好方法是什麼?代碼會很棒。
謝謝!
在您的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}"/>
感謝
只是把我在MIN數值我的WPF代碼實現的方式是0和MAX的數值爲99。 希望這可以幫助
<!-- WPF Code Sample.xaml -->
<TextBox
Text="1"
Width="20"
PreviewTextInput="PreviewTextInputHandler"
IsEnabled="True"/>
// 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);
}
非常感謝。有效。我只需切換minValue = maxValue。 –
很高興它的工作。你可能想接受答案;) – Nitin