DataGridTemplateColumn读取文本框

时间:2019-02-22 15:12:58

标签: c# wpf

我有一个数据网格,最后有3个DataGridTemplateColumn: enter image description here

<DataGrid x:Name="dataGrid" HorizontalAlignment="Left" Height="464" Margin="90,97,0,0" VerticalAlignment="Top" Width="840" AutoGenerateColumns="False">
  <DataGrid.Columns>
    <DataGridTextColumn Header="Codice" Binding="{Binding Codice}" />
    <DataGridTextColumn Header="Descrizione" Binding="{Binding Descrizione}" />
    <DataGridTextColumn Header="Giacenza" Binding="{Binding Giacenza}" />
    <DataGridTextColumn Header="In Ordine" Binding="{Binding In Ordine}" />

    <DataGridTemplateColumn>
    <DataGridTemplateColumn.CellTemplate>
        <DataTemplate>
           <Button Click="Togli_Click">-</Button>
        </DataTemplate>
    </DataGridTemplateColumn.CellTemplate>
  </DataGridTemplateColumn>
  <DataGridTemplateColumn>
     <DataGridTemplateColumn.CellTemplate>
       <DataTemplate>
           <TextBox Width="25" x:Name="txtQTA">0</TextBox>
       </DataTemplate>
     </DataGridTemplateColumn.CellTemplate>
  </DataGridTemplateColumn>
  <DataGridTemplateColumn>
     <DataGridTemplateColumn.CellTemplate>
        <DataTemplate>
            <Button Click="Aggiungi_Click">+</Button>
        </DataTemplate>
     </DataGridTemplateColumn.CellTemplate>
   </DataGridTemplateColumn>
 </DataGrid.Columns>
</DataGrid>

如果我单击“ +”或“-”,则文本框“ txtQTA”将递增或递减。我没有找到按钮单击中的文本框。 谢谢

1 个答案:

答案 0 :(得分:0)

这是我找到的解决方案:

private void Aggiungi_Click(object sender, RoutedEventArgs e)
        {
            TextBox txt = FindVisualChildByName<TextBox>(dataGrid.ItemContainerGenerator.ContainerFromIndex(dataGrid.SelectedIndex) as DataGridRow, "txtQTA", dataGrid.SelectedIndex);
            txt.Text = "Writing";
        }
        public T FindVisualChildByName<T>(DependencyObject parent, string name, int nRiga) where T : DependencyObject
        {

            for (int i = 0; i < VisualTreeHelper.GetChildrenCount(parent); i++)



            {

                var child = VisualTreeHelper.GetChild(parent, i);

                string controlName = child.GetValue(Control.NameProperty) as string;

                if (controlName == name)

                {

                    return child as T;

                }

                else

                {

                    T result = FindVisualChildByName<T>(child, name, nRiga);

                    if (result != null)

                        return result;

                }

            }

            return null;

        }