WPF Datagrid Column TextBox 允许可为空的数字输入 C#

WPF Datagrid Column TextBox Allow nullable numerical input C#

我有一个 Datagrid col 绑定一个可为 null 的 int。

<DataGridTextColumn Header = "OVR QTY" Width = "5*" Binding = "{Binding OVERRIDE_QTY, UpdateSourceTrigger = PropertyChanged, StringFormat=N0}"  ElementStyle="{StaticResource STRIKE_THROUGH}">
    <DataGridTextColumn.EditingElementStyle>
        <Style TargetType="{x:Type TextBox}">                                        
            <EventSetter Event="PreviewTextInput" Handler="ODQTY_PreviewTextInput">
            </EventSetter>                                        
        </Style>
    </DataGridTextColumn.EditingElementStyle>
</DataGridTextColumn>

在代码中,我尝试将其限制为数字和 null。

Regex regex = new Regex("^[.][0-9]+$|^[0-9]*[.]{0,1}[0-9]*$|^[0-9]*[ ][0-9]*[/]{0,1}[1-9]*$|^[1-9]*[/]{0,1}[1-9]*$");

private void ODQTY_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
    TextBox tb = sender as TextBox;
        var result = tb.Text.Insert(tb.SelectionStart, e.Text);
        e.Handled = string.IsNullOrEmpty(result) 
            || !regex.IsMatch(result);
}

当我在单元格中键入 1,然后键入退格键删除 1 时,数据网格单元格不接受空白,我认为它是空的(如果我错了,请更正)。不确定为什么以及如何让它在单元格中接受 null。

在你的xaml

<DataGridTextColumn Header = "OVR QTY" Width = "5*" Binding = "{Binding OVERRIDE_QTY, UpdateSourceTrigger = PropertyChanged, .......

添加这个:

TargetNullValue=''

看起来像这样

<DataGridTextColumn Header = "OVR QTY" Width = "5*" Binding = "{Binding OVERRIDE_QTY, UpdateSourceTrigger = PropertyChanged, TargetNullValue='', StringFormat=N0}"  ElementStyle="{StaticResource STRIKE_THROUGH}">

我认为它会起作用。