允许xaml-WPF中的文本框使用非0 uint
我在xaml中有一个文本框。下面是.cs文件中的代码:允许xaml-WPF中的文本框使用非0 uint,wpf,xaml,c#-4.0,Wpf,Xaml,C# 4.0,我在xaml中有一个文本框。下面是.cs文件中的代码: public static readonly DependencyProperty dp = DependencyProperty.Register( "result", typeof( uint ), typeof( ui ), new FrameworkPropertyMetadata( ( uint )100, new PropertyChange
public static readonly DependencyProperty dp =
DependencyProperty.Register(
"result", typeof( uint ), typeof( ui ),
new FrameworkPropertyMetadata( ( uint )100, new PropertyChangedCallback( ResultChanged ) ) );
private static void ResultChanged(
DependencyObject d, DependencyPropertyChangedEventArgs e )
{
var input = ( ui )d;
var value = ( uint )e.NewValue;
}
上面的代码非常有效,它不允许在文本框中输入任何字母或无效字符。但如何更改上述代码,使用户无法在文本框中输入“0”?所以基本上允许除0之外的所有uint 有很多方法可以做到这一点……最简单、最简单的方法就是使用扩展WPF工具包中的NumericUpDown控件……设置最小/最大范围,然后进行排序
如果你真的想自己做逻辑,那么 根据您的需要/要求,您可以在依赖项属性的寄存器中指定“强制回调”和/或“验证回调”,即是否需要将值固定到某个范围,或向用户显示错误指示器 “强制”是指将值调整为其他值,例如,在本例中,您可能决定将任何值0调整为1(或可能为null) “验证”是检查值的地方,你说它是否正确(通过返回true或false)…如果你返回false…则引发异常 您可以对DependencyProperty的绑定使用ValidatesOnException,以便通过显示ErrorTemplate的方式将该“错误”传播到用户界面(默认情况下,控件周围显示红色边框)
您还可以使用不同的技术,如ValidationRules、MaskedTextBox和PreviewText
public static readonly DependencyProperty dp =
DependencyProperty.Register(
"result", typeof( uint ), typeof( ui ),
new FrameworkPropertyMetadata(
( uint )100,
null,
new CoerceValueCallback( ResultCoerceValue )
)
);
private static object ResultCoerceValue
(DependencyObject depObj, object baseValue)
{
uint coercedValue = (uint)baseValue;
if ((uint)baseValue == 0)
coercedValue = 1; // might be able to set to null...but not sure on that.
return coercedValue;
}