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

Bad*_*rul 6 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>
Run Code Online (Sandbox Code Playgroud)

代码背后:

 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;                         
 }   
Run Code Online (Sandbox Code Playgroud)

你能不能告诉我怎么办?

She*_*dan 16

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

ContentPresenter contentPresenter = FindVisualChild<ContentPresenter>(yourListBoxItem);
Run Code Online (Sandbox Code Playgroud)

然后得到DataTemplate来自ContentPresenter:

DataTemplate yourDataTemplate = contentPresenter.ContentTemplate;
Run Code Online (Sandbox Code Playgroud)

然后得到MediaElement来自DataTemplate:

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

有关详细信息,请参阅MSDN上的" FrameworkTemplate.FindName方法"页面.

  • 值得指出的是,FindVisualChild <>()方法在WPF或.NET中不是_natively_可用的.您需要手动添加它,请参阅以下SO答案以获取示例:http://stackoverflow.com/a/25229554/2737435 (2认同)