问题
How to access a named control that is in the content template of the contentpresenter. how to access the webview control(x:name=detView) from cs file.
<ContentPresenter
x:Name="DetailContentPresenter"
Grid.Row="0"
BorderBrush="{ThemeResource SystemControlForegroundBaseLowBrush}"
Content="{x:Bind coll.SelectedItem,Mode=OneWay}">
<ContentPresenter.ContentTemplate>
<DataTemplate x:DataType="data:coll_Details" x:Name="ttt">
<Grid>
<WebView DefaultBackgroundColor="#F5F5F5" x:Name="detView" Source="ms-appx-web:///Assets/Web/collDetails.html"/>
</Grid>
</DataTemplate>
</ContentPresenter.ContentTemplate>
<ContentPresenter.ContentTransitions>
<TransitionCollection/>
</ContentPresenter.ContentTransitions>
</ContentPresenter>
回答1:
If you are using ContentPresenter as ControlTemplate like the example of Official Documentation.
You can get the template through the controlName.ContentTemplateRoot
. I made a demo from the Example of official documentation above, and put a webview inside the DataTemplate.
MainPage.xaml:
<Page.Resources>
<Style TargetType="HyperlinkButton" x:Key="myStyle" >
...
<Setter Property="Template" x:Name="presenterSetter">
<Setter.Value>
<ControlTemplate TargetType="HyperlinkButton">
<Grid x:Name="rootGrid">
...
<Border x:Name="Border"
Background="{TemplateBinding Background}"
BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}"
Margin="3">
<ContentPresenter x:Name="MyContentPresenter"
Content="{TemplateBinding Content}"
ContentTransitions="{TemplateBinding ContentTransitions}"
HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
VerticalAlignment="{TemplateBinding VerticalContentAlignment}"
>
<ContentPresenter.ContentTemplate>
<DataTemplate x:Name="ttt">
<Grid>
<WebView Source="ms-appx-web:///Assets/Web/default.html" Name="myWebView"/>
</Grid>
</DataTemplate>
</ContentPresenter.ContentTemplate>
</ContentPresenter>
</Border>
<!--focus visuals omitted-->
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</Page.Resources>
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<StackPanel VerticalAlignment="Bottom">
<HyperlinkButton Name="myHyperlink" Style="{StaticResource myStyle}">This is a link</HyperlinkButton>
<Button Click="Button_Click" Name="myBtn">Click Me</Button>
</StackPanel>
</Grid>
And I can get the WebView using the codes below:
private void Button_Click(object sender, RoutedEventArgs e)
{
var myView= ((Grid)myHyperlink.ContentTemplateRoot).Children[0] as WebView;
}
回答2:
In C#, use this code to find any control which is present in your ContentPresenter
.
If a TextBlock
is present in your ContentPresenter
then first create a object of the TextBlock
then cast it and then find control.
TextBlock myTextBlock = (TextBlock)ttt.FindName(“textBlock”, DetailContentPresenter);
来源:https://stackoverflow.com/questions/38196392/accessing-a-control-which-is-in-a-contentpresenter-in-c-sharp