开发者

getting a reference to a MediaElement inside an ItemsControl (WPF)

this is a known issue with ItemsControl although I couldn't find a solution :( .

XAML

    <ItemsControl x:Name="myItemsControl" ItemsSource ="{Binding videos}" Grid.ColumnSpan="2">
        <ItemsControl.Resources>
            <DataTemplate x:Name="myDataTemplate" DataType="{x:Type sys:String}">
              开发者_如何学Go  <Grid x:Name="sp" Width="300" Height="200">
                    <MediaElement x:Name="myvideo" Loaded="myvideo_Loaded" UnloadedBehavior="Stop"  ScrubbingEnabled="True" Stretch="Fill" Source="{Binding}" LoadedBehavior= "Play">
                    </MediaElement>
                </Grid>
            </DataTemplate>
            </ItemsControl.Resources>
        <ItemsControl.ItemsPanel>
            <ItemsPanelTemplate>
                <mt:TouchablePanel/>
            </ItemsPanelTemplate>
        </ItemsControl.ItemsPanel>
    </ItemsControl>

</Grid>

so in behind code I want to do something like

private void myvideo_Loaded(object sender, RoutedEventArgs e)
{
    //myvideo.Play();
    // myvideo.Pause();
}

I commented it out to be able to compile.


In the event handler, you can access the MediaElement through the sender parameter

private void myvideo_Loaded(object sender, RoutedEventArgs e)
{
    MediaElement myVideo = sender as MediaElement;
    if (myVideo != null)
    {
        myvideo.Play();
    }
}

If you want to access the MediaElement for a specific item in the ItemsControl, you can use the ItemContainerGenerator :

MediaElement myVideo = null;
FrameworkElement container = myItemsControl.ItemContainerGenerator.ContainerFromItem(someItem) as FrameworkElement;
if (container != null)
{
    // Note: this works for an ItemsControl, not for a ListBox or ListView...
    ContentPresenter presenter = container as ContentPresenter;
    if (presenter != null)
    {
        myVideo = presenter.ContentTemplate.FindName(myVideo)
    }
}


Maybe you'll get better answer here, but if not, you can always wrap your MediaElement control into UserControl. In the user control you subscribe to all events you need, and then use the user control inside data template.

:) Hope this helps.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜