如何从代码后面访问数据模板中的控件?

时间:2013-10-15 11:20:03

标签: c# wpf

您好MediaElement内有DataTemplate,但我无法从后面的代码中访问它。

我在下面发布xaml代码:

<Grid>
<Grid.ColumnDefinitions>
    <ColumnDefinition Width="605*"/>
    <ColumnDefinition Width="151*"/>
</Grid.ColumnDefinitions>
<GroupBox Header="My Videos" Height="177" VerticalAlignment="Top" Margin="5,320,5,0" Grid.ColumnSpan="2">
    <ListBox x:Name="VideoList" ItemsSource="{Binding Videos }" Width="auto" Height=" auto" Margin="0,0,0,0" Grid.ColumnSpan="2" >
        <DataTemplate x:Name="DTVideos">
            <ListBoxItem Name="lbivid1" BorderThickness="2"  Width="240" Selected="lbivid_Selected" >
                <MediaElement Name="vidList" Height="150" Width="150" Source="{Binding SourceUri}" Position="00:00:05" LoadedBehavior="Pause" ScrubbingEnabled="True"/>
            </ListBoxItem>
        </DataTemplate>
        <ItemsControl.ItemsPanel>
            <ItemsPanelTemplate>
                <StackPanel Orientation="Horizontal" Margin="0,0,0,0"/>
            </ItemsPanelTemplate>
        </ItemsControl.ItemsPanel>
    </ListBox>
</GroupBox>     
<GroupBox Header="Preview" Height="320" Width="400" VerticalAlignment="Top" DockPanel.Dock="Left">
    <MediaElement x:Name="videoPreview" HorizontalAlignment="Left" Height="300" VerticalAlignment="Top" Width="388"/>
</GroupBox>

代码背后:

 private void lbivid_Selected(object sender, RoutedEventArgs e)
 {   
    imagePreview.Visibility = Visibility.Hidden;   
    string urlStr = (VidList.Source).ToString();          
    Uri temp = new Uri(UrlStr);
    videoPreview.Source = temp;                         
 }   

你们中的任何人都可以告诉我怎么做?

2 个答案:

答案 0 :(得分:15)

应该能够使用FrameworkTemplate.FindName方法访问您的控件...首先,从其中一个ContentPresenter获取ListBoxItem:< / p>

ContentPresenter contentPresenter = FindVisualChild<ContentPresenter>(yourListBoxItem);

然后从DataTemplate获取ContentPresenter

DataTemplate yourDataTemplate = contentPresenter.ContentTemplate;

然后从MediaElement获取DataTemplate

MediaElement yourMediaElement = yourDataTemplate.FindName("vidList", contentPresenter) 
as MediaElement;
if (yourMediaElement != null)
{
    // Do something with yourMediaElement here
}

有关详情,请参阅MSDN上的FrameworkTemplate.FindName Method页面。

答案 1 :(得分:0)

您的事件处理程序中有发件人,即ListBoxItem,MediaElement是ListBoxItem.Content

var mediaElement = ((ListBoxItem)sender).Content as MediaElement;
if (mediaElement != null) ...