问题
Hello guys I am trying to get TextBox Named "txtQty" value from DataGridTemplateColum
Here is the code, Hope someone Helps me....
.XML
<DataGrid x:Name="dataGridMain">
<DataGrid.Columns>
<DataGridTextColumn Header="Id" Binding="{Binding Id}" IsReadOnly="True" Visibility="Hidden"/>
<DataGridTextColumn Header="Name" Binding="{Binding PName}" IsReadOnly="True"/>
<DataGridTemplateColumn Header="Qty" >
<DataGridTemplateColumn.CellTemplate >
<DataTemplate >
<StackPanel Orientation="Horizontal">
<TextBox x:Name="txtQty"/>
</StackPanel>
</DataTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
I tried using this code
DataRowView dt = dataGridMain.SelectedItem as DataRowView;
String value = dt["Qty"].ToString());
回答1:
After some struggle I found this solution helpful.....
int i=5; //Set this equal to desired column index....
ContentPresenter myCp = dataGridMain.Columns[i].GetCellContent(dataGridMain.SelectedItem) as ContentPresenter;
var myTemplate = myCp.ContentTemplate;
TextBox mytxtbox = myTemplate.FindName("txtQty", myCp) as TextBox;
MessageBox.Show(mytxtbox.Text);
回答2:
My guess is that you are trying to access the selected row here is the answer for that https://stackoverflow.com/a/3913791/1449779 also don't forget to bind the text box as DonBoitnott comment
来源:https://stackoverflow.com/questions/52745984/wpf-get-textbox-value-from-datagridtemplatecolumn