Access XAML Control In DataTemplate From CodeBehind?

前端 未结 2 1551
闹比i
闹比i 2021-01-22 13:08

I have a control that I am unable to access in the codebehind, and I believe it is because it is defined in a DataTempalte.

The overall control is a slide show carousel.

2条回答
  •  闹比i
    闹比i (楼主)
    2021-01-22 13:51

    WPF provides a simple and straightforward way to access named elements that are generated from DataTemplates. It is explained in the MSDN article How to: Find DataTemplate-Generated Elements.

    Assumed that your AutoScrollCarousel is derived from ItemsControl, you would get the ContentPresenter that is the container of an item like this:

    AutoScrollCarousel carousel = ...
    object item = ...
    var contentPresenter =
        carousel.ItemContainerGenerator.ContainerFromItem(item) as ContentPresenter;
    

    From the ContentPresenter you would get the named element in the DataTemplate by means of the FindName method:

    var dataTemplate = contentPresenter.ContentTemplate;
    var mediaPlayer = dataTemplate.FindName("MediaPlayer", contentPresenter) as MediaElement;
    

提交回复
热议问题