Access XAML Control In DataTemplate From CodeBehind?

前端 未结 2 1549
闹比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条回答
  • 2021-01-22 13:27

    I would normally recommend not to touch UIElements from code... but the MediaElement is a special case... maybe you should wrap the whole template inside a usercontrol (maybe with some custom DepProps) and that will give you better control over the whole thing.

    Edit: Another approach would be to create a Behavior with a couple of properties (such as IsPlaying) and manipulate the mediaelement from there. Then you could use this behavior in the XAML of the DataTemplate, with no need for code behind or usercontrols.

    0 讨论(0)
  • 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;
    
    0 讨论(0)
提交回复
热议问题