<TextBox x:Name="txt_SewagePrice" Grid.Row="3" Grid.Column="1"
VerticalContentAlignment="Center"
PreviewTextInput="txt_PreviewTextInput"
input:InputMethod.IsInputMethodEnabled="False"
Margin=" 10,5,10,5"
Height="26"
MaxLength="10"
Style="{StaticResource OuterGlowStyle}"
/>
private void txt_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
Regex re = new Regex("[^0-9.-]+");
e.Handled = re.IsMatch(e.Text);
var textBox = e.OriginalSource as TextBox;
if (textBox != null)
{
if (!string.IsNullOrWhiteSpace(textBox.Text))
{
if (textBox.Text.Substring(textBox.Text.Length - 1) != ".")
{
if (!textBox.Text.Contains("."))
{
textBox.MaxLength = 10;
}
if (decimal.TryParse(textBox.Text, out var anyAmount))
{
// Text成功轉爲deciml後邏輯
}
}
else
{
textBox.MaxLength = textBox.Text.Length + 2;
}
}
else
{
// Text爲空邏輯
}
}
}