C# 将值验证为WPF中文本框中的数字

C# 将值验证为WPF中文本框中的数字,c#,wpf,C#,Wpf,我正在将float?属性绑定到WPF应用程序中的TextBox。我还准备了验证数据错误 当我输入无效的非数字值时,文本框的边框会变成不同的颜色,因为它无法将该值转换为浮点。因此该值绑定到null 我的问题是-如何阻止它绑定到null?我真的想给出一个错误,比如“请只输入数值”。谢谢。样式是数据输入验证的最佳方法。您只需将此样式复制到窗口或用户控件。 注意:我使用工具提示,但您可以使用自己的方法向用户显示通知: <Window.Resources> <Style Targ

我正在将
float?
属性绑定到WPF应用程序中的
TextBox
。我还准备了
验证数据错误

当我输入无效的非数字值时,
文本框
的边框会变成不同的颜色,因为它无法将该值转换为
浮点
。因此该值绑定到
null


我的问题是-如何阻止它绑定到
null
?我真的想给出一个错误,比如“请只输入数值”。谢谢。

样式是数据输入验证的最佳方法。您只需将此样式复制到窗口或用户控件。
注意:我使用工具提示,但您可以使用自己的方法向用户显示通知:

<Window.Resources>
    <Style TargetType="{x:Type TextBox}">
        <Style.Triggers>
            <Trigger Property="Validation.HasError" Value="true">
                <Setter Property="Background" Value="Pink"/>
                <Setter Property="Foreground" Value="Black"/>
            </Trigger>
        </Style.Triggers>
        <Setter Property="Validation.ErrorTemplate">
            <Setter.Value>
                <ControlTemplate>
                    <Grid>
                        <Polygon Points="9,9 9,0 0,0" Stroke="Red" StrokeThickness="1" Fill="Red" HorizontalAlignment="Right"  VerticalAlignment="Top"
                                     ToolTip="Please enter numeric values only"/>
                        <AdornedElementPlaceholder x:Name="valAdorner" VerticalAlignment="Center">
                            <Border BorderBrush="red" BorderThickness="1" />
                        </AdornedElementPlaceholder>
                    </Grid>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
</Window.Resources>

样式是数据输入验证的最佳方法。您只需将此样式复制到窗口或用户控件。
注意:我使用工具提示,但您可以使用自己的方法向用户显示通知:

<Window.Resources>
    <Style TargetType="{x:Type TextBox}">
        <Style.Triggers>
            <Trigger Property="Validation.HasError" Value="true">
                <Setter Property="Background" Value="Pink"/>
                <Setter Property="Foreground" Value="Black"/>
            </Trigger>
        </Style.Triggers>
        <Setter Property="Validation.ErrorTemplate">
            <Setter.Value>
                <ControlTemplate>
                    <Grid>
                        <Polygon Points="9,9 9,0 0,0" Stroke="Red" StrokeThickness="1" Fill="Red" HorizontalAlignment="Right"  VerticalAlignment="Top"
                                     ToolTip="Please enter numeric values only"/>
                        <AdornedElementPlaceholder x:Name="valAdorner" VerticalAlignment="Center">
                            <Border BorderBrush="red" BorderThickness="1" />
                        </AdornedElementPlaceholder>
                    </Grid>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
</Window.Resources>


如果要显示消息,只需在文本框中放置event textchanged并在其中检查有效数字。如果要显示消息,只需在文本框中放置event textchanged并在其中检查有效数字。