如何访问 DataTemplate 的控件

How do I access a control of a DataTemplate

我在用户控件资源中有两个不同的数据模板。一个 DataTemplate 包含图像控件,另一个 DataTemplate 包含媒体元素控件。每个 DataTemplate 的 DataType 分别代表一个 ImageViewModel 和一个 VideoViewModel。在我的用户控件中有一个包含 ContentControl 的网格。内容控件的内容 属性 绑定到表示应使用的当前视图模型的 属性。

想法是根据当前视图模型更改网格的内容

<UserControl.Resources>
    <DataTemplate DataType="{x:Type vm:ImageScreensaverViewModel}">
        <Image Source="{Binding Image}" Stretch="Uniform"/>
    </DataTemplate>

    <DataTemplate DataType="{x:Type vm:VideoScreensaverViewModel}">
        <MediaElement x:Name="Player" Source="{Binding Video}" LoadedBehavior="Play" />
    </DataTemplate>
</UserControl.Resources>

<UserControl.CommandBindings>
    <CommandBinding Command="MediaCommands.Pause" Executed="PausePlayer" CanExecute="CanExecute"/>
    <CommandBinding Command="MediaCommands.Play" Executed="PlayPlayer" CanExecute="CanExecute"/>
</UserControl.CommandBindings>

<Grid>
    <ContentControl x:Name="ScreanSaverContent" Content="{Binding CurrentVm}"/>
</Grid>

效果很好,但我需要在代码后面访问 MediaElement 以便我可以控制媒体播放器(播放、停止、暂停)

我已经尝试过 hier 上发布的解决方案,但没有成功。我只能通过内容 属性.

访问选定的视图模型

尝试使用这段代码访问 ContentPresenter 中的控件:

    public static FrameworkElement GetControlByName(DependencyObject parent, string name)
    {
        int count = VisualTreeHelper.GetChildrenCount(parent);
        for (var i = 0; i < count; ++i)
        {
            var child = VisualTreeHelper.GetChild(parent, i) as FrameworkElement;
            if (child != null)
            {
                if (child.Name == name)
                {
                    return child;
                }
                var descendantFromName = GetControlByName(child, name);
                if (descendantFromName != null)
                {
                    return descendantFromName;
                }
            }
        }
        return null;
    }