How to change Text of TextBlock which is in DataTe

2019-04-11 03:05发布

问题:

I have Datagrid which is clicking by mouse in each row is showing data grid row details. here is code,

Microsoft.Windows.Controls.DataGridRow row = (Microsoft.Windows.Controls.DataGridRow)(DataGrid1.ItemContainerGenerator.ContainerFromItem(DataGrid1.SelectedItem));


        DataGridDetailsPresenter presenter = FindVisualChild<DataGridDetailsPresenter>(row);


        DataTemplate template = presenter.ContentTemplate;
        TextBlock txt = (TextBlock)template.FindName("rowdetails", presenter);
        txt.Text = retString;

And also I have Checkbox, when you check it, it should show all row details. I am trying this code for showing all rowdetails

if ((bool)chkboxRowDetails.IsChecked)
            {
                DataGrid1.RowDetailsVisibilityMode = Microsoft.Windows.Controls.DataGridRowDetailsVisibilityMode.Visible;

                for (int i = 0; i < DataGrid1.Items.Count-1; i++)
                {
                    Microsoft.Windows.Controls.DataGridRow row = (Microsoft.Windows.Controls.DataGridRow)(DataGrid1.ItemContainerGenerator.ContainerFromIndex(i));
                    DataGridDetailsPresenter presenter = FindVisualChild<DataGridDetailsPresenter>(row);
                    DataTemplate template =presenter.ContentTemplate;

                    TextBlock txt = (TextBlock)template.FindName("rowdetails", presenter);
                    txt.Text = retString;


                }

But it is giving error. "This operation is valid only on elements that have this template applied." Showing in line TextBlock txt = (TextBlock)template.FindName("rowdetails", presenter); Do you have any idea what is wrong in my code. I want to show all row details by checking checkbox. My Data template is here

<WpfToolkit:DataGrid.RowDetailsTemplate>

            <DataTemplate>

                <StackPanel HorizontalAlignment="Stretch" Orientation="Vertical" Margin="5">
                    <TextBlock Foreground="CadetBlue" FontSize="14"
                        TextWrapping="Wrap" Name="rowdetails" HorizontalAlignment="Stretch"
                        />
                </StackPanel>
            </DataTemplate>


        </WpfToolkit:DataGrid.RowDetailsTemplate>

回答1:

I solved this problem by adding some codes in row details load. Here is code.

        TextBlock txt1 = e.DetailsElement.FindName("rowdetails") as TextBlock;
        txt1.Text = retString; // where retString is variable string.