无法识别DataGrid-RowDetailsTemplate内的stackpanel中的变量

时间:2015-05-23 12:02:46

标签: c# wpf datagrid rowdetailstemplate

我在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 个答案:

答案 0 :(得分:0)

假设您为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;
    }