DataGrid-RowDetailsTemplate 内的堆栈面板中的变量无法识别

Posted

技术标签:

【中文标题】DataGrid-RowDetailsTemplate 内的堆栈面板中的变量无法识别【英文标题】:Variable in stackpanel inside of DataGrid-RowDetailsTemplate is not recognize 【发布时间】:2015-08-05 09:43:26 【问题描述】:

我在 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#后面:

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

谢谢大家。

【问题讨论】:

【参考方案1】:

假设你命名你的DataGriddataGrid,那么这就是你需要的:

    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;
    

【讨论】:

以上是关于DataGrid-RowDetailsTemplate 内的堆栈面板中的变量无法识别的主要内容,如果未能解决你的问题,请参考以下文章