DataGrid-RowDetailsTemplate内部的stackpanel变量不被识别

本文关键字:识别 变量 stackpanel 内部 DataGrid-RowDetailsTemplate | 更新日期: 2023-09-27 17:50:27

我在DataGrid.RowDetailsTemplate中有堆栈面板。在堆栈面板中,我有文本框和按钮。c#代码中的按钮函数试图使用文本框中的值,但出现错误:

"名称'toCheck'在当前上下文中不存在".

我怎么做才能使用文本框中的值?

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");
            }
        }

谢谢大家

DataGrid-RowDetailsTemplate内部的stackpanel变量不被识别

假设您将DataGrid命名为dataGrid,那么这就是您需要的:

    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;
    }