How to Get element inside the content control

后端 未结 2 448
面向向阳花
面向向阳花 2021-01-13 17:01

I need to find the element inside the content control :



        
2条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-01-13 17:47

    Basically, you need to provide an element that (as the error says) has the Template applied. Your ccBloodGroup control is inside the DataTemplate and so clearly, does not have this Template applied to it.

    For example, an element that might have this Template applied to it would be the ContentPresenters of the items in the YourChoices collection that are using this DataTemplate to define what they look like in the UI.

    You can find out full details as usual on MSDN, with a detailed example on the FrameworkTemplate.FindName Method page, but it goes something like this... from the example on the linked page:

    // Getting the currently selected ListBoxItem 
    // Note that the ListBox must have 
    // IsSynchronizedWithCurrentItem set to True for this to work
    ListBoxItem myListBoxItem = (ListBoxItem)(myListBox.ItemContainerGenerator.
        ContainerFromItem(myListBox.Items.CurrentItem));
    
    // Getting the ContentPresenter of myListBoxItem
    ContentPresenter myContentPresenter = FindVisualChild(myListBoxItem);
    
    // Finding textBlock from the DataTemplate that is set on that ContentPresenter
    DataTemplate myDataTemplate = myContentPresenter.ContentTemplate;
    TextBlock myTextBlock = (TextBlock)myDataTemplate.FindName("textBlock", 
        myContentPresenter);
    
    // Do something to the DataTemplate-generated TextBlock
    MessageBox.Show("The text of the TextBlock of the selected list item: "
    + myTextBlock.Text);
    

    The FindVisualChild method is shown on the linked page.

提交回复
热议问题