如何从代码数据模板中访问控制的背后?
您好我有一个的MediaElement
在的DataTemplate
,但我无法从代码访问它的后面。
Hi I have a MediaElement
within the DataTemplate
but I am unable to access it from the code behind.
我张贴下面的XAML代码:
I am posting xaml code below:
<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;
}
能否你们谁能告诉我怎样才能做到呢?
Can anyone of you please tell me how can it be done?
您应的能够使用访问您的控制 FrameworkTemplate.FindName
方法...首先,获得 ContentPresenter
从 ListBoxItem的
取值之一:
You should be able to access your control using the FrameworkTemplate.FindName
method... first, get the ContentPresenter
from one of the ListBoxItem
s:
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
}
请参见 FrameworkTemplate.FindName
方法在MSDN上获得更多信息。
Please see the FrameworkTemplate.FindName
Method page on MSDN for more information.