WPF中的字符串格式只能插入0或1

问题描述 投票:1回答:2

我的要求是,要使用字符串格式插入的文本框值应为0或1我已经尝试了事件背后的代码工作正常,但我必须在xaml中使用字符串格式进行验证,而不是事件。所以帮帮我。

正在工作

<TextBox PreviewTextInput="NumberValidationTextBox"  MaxLength="1">

private void NumberValidationTextBox(object sender, TextCompositionEventArgs e)
{
     Regex regex = new Regex("[^0-1]+");
     e.Handled = regex.IsMatch(e.Text);
}

不起作用

<TextBox Text="{Binding Value,StringFormat=N2}" />
<TextBox Text="{Binding Value,StringFormat={}{0:#,#.00}}" />
<TextBox Text="{Binding Value,StringFormat={}{0:#,0.0}}"/>
wpf xaml string-formatting
2个回答
0
投票

您在桌子上有几个选择。

  • 以这种方式编写ValueConverter,您将在XAML中一次又一次地编写代码。
  • 在属性设置器中执行此操作,如果输入的不是0或1,则将其清除。
  • 您也可以在这种情况下使用一些更合适的控件,例如复选框,甚至是单选按钮。

0
投票

此XAML会将输入调整为仅01

<TextBox Text="{Binding Value, UpdateSourceTrigger=PropertyChanged, StringFormat={}{0:1;1;0}}"/>

Value必须为数字,否则StringFormat将不起作用。

© www.soinside.com 2019 - 2024. All rights reserved.