I have stack panel inside DataGrid.RowDetailsTemplate. In the stack panel I have text Box and button. The function of the button in the c# code behind tried to use the value from the text box but there is an error :
"The name 'toCheck' does not exist in the current context".
What can I do so that I could use the value from the text box?
xaml :
<DataGrid.RowDetailsTemplate >
<DataTemplate >
<Border>
<StackPanel>
<Label Name="headLine" Content="what do you want to change:" HorizontalAlignment="Left" Height="40" Margin="10,50,0,0" VerticalAlignment="Top" Width="170"/>
<TextBox Name="toCheck" HorizontalAlignment="Left" Text="{Binding Name}" Height="23" Margin="34,0,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="130"/>
<Button Name="check" Content="Check" HorizontalAlignment="Left" Margin="105,50,0,0" VerticalAlignment="Top" Width="75" Click="check_Click"/>
</StackPanel>
</Border>
</DataTemplate>
</DataGrid.RowDetailsTemplate>
c# behind :
public partial class window1 : UserControl
{
public window1 ()
{
InitializeComponent();
}
private void check_Click(object sender, RoutedEventArgs e)
{
string needCheck = toCheck.Text;
if (needCheck == "abc")
{
MessageBox.Show("its abc");
}
}
thank you all.
Assuming you name your DataGrid
dataGrid, then this is what you need:
private void check_Click(object sender, RoutedEventArgs e)
{
DataGridRow dgRow = (DataGridRow)(dataGrid.ItemContainerGenerator.ContainerFromItem(dataGrid.SelectedItem));
if (dgRow == null) return;
DataGridDetailsPresenter dgdPresenter = FindVisualChild<DataGridDetailsPresenter>(dgRow);
DataTemplate template = dgdPresenter.ContentTemplate;
TextBox textBox = (TextBox)template.FindName("toCheck", dgdPresenter);
string needCheck = textBox.Text;
if (needCheck == "abc")
{
MessageBox.Show("its abc");
}
}
public static T FindVisualChild<T>(DependencyObject obj) where T : DependencyObject
{
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++)
{
DependencyObject child = VisualTreeHelper.GetChild(obj, i);
if (child != null && child is T)
return (T)child;
else
{
T childOfChild = FindVisualChild<T>(child);
if (childOfChild != null)
return childOfChild;
}
}
return null;
}