DataGridTextColumn中的EditingElementStyle

时间:2018-09-25 13:46:32

标签: c# wpf datagrid

我需要能够与DataGrid中的哪个列进行区分,TextBox已被编辑:

<DataGridTextColumn Header="No" Binding="{Binding NumberOfItems}">
    <DataGridTextColumn.EditingElementStyle>
        <Style TargetType="{x:Type TextBox}"  x:Name="NumOfItems">   
            <Setter Property="MaxLength" Value="2"/>
         </Style>
    </DataGridTextColumn.EditingElementStyle>
</DataGridTextColumn>

<DataGridTextColumn Header="Role" Binding="{Binding Role}" Width="0.75*">
    <DataGridTextColumn.EditingElementStyle>
        <Style TargetType="{x:Type TextBox}"  x:Name="Role">
            <Setter Property="MaxLength" Value="30"/>
         </Style>
    </DataGridTextColumn.EditingElementStyle>
</DataGridTextColumn>

以便我可以使用正确的信息更新数据库。我尝试使用x:Name,但是在下面的代码中,名称始终为空

private void dgItems_CellEditEnding(object sender, 
DataGridCellEditEndingEventArgs e)
    {
        if(e.EditingElement is TextBox)
        {
             TextBox t = e.EditingElement as TextBox;
             ..........
             if (t.Name == "Role")
             //do this
             else if (t.NumOfItems)
             //do this
    }

感谢您的帮助

1 个答案:

答案 0 :(得分:1)

您可以在Tag中设置Style属性:

<Style TargetType="{x:Type TextBox}">
    <Setter Property="MaxLength" Value="30"/>
    <Setter Property="Tag" Value="Role"/>
</Style>

if (t.Tag?.ToString() == "Role")