在Windows Phone 8中以编程方式获取Pivot Header中的按钮

时间:2013-04-15 12:45:06

标签: silverlight xaml windows-phone-8 windows-phone

总结:我需要从一个模板被定义为静态资源的数据透视表中检索一个按钮(以便附加一个点击处理程序)。我怎么能这样做?

一些视图包含一个数据透视控件,这些支点的样式在App.xaml中定义为资源。

以下是多页Pivot的XAML:

<phone:Pivot Title="Onaylar" Name="pivot" Style="{StaticResource MyPivotStyle}">
    <phone:PivotItem Header="first pivot item">
        <TextBlock Foreground="{StaticResource NavyTextColor}" Margin="10,0,0,0" Text="first pivot item"></TextBlock>
    </phone:PivotItem>

    <phone:PivotItem Header="second pivot item">
        <TextBlock Foreground="{StaticResource NavyTextColor}" Margin="10,0,0,0" Text="second pivot item"></TextBlock>
    </phone:PivotItem>
    <phone:PivotItem Header="third pivot item">
        <TextBlock Foreground="{StaticResource NavyTextColor}" Margin="10,0,0,0" Text="third pivot item"></TextBlock>
    </phone:PivotItem>
</phone:Pivot>

这是App.xaml中定义的pivot的样式(为方便起见缩短):

<Style x:Key="MyPivotStyle" TargetType="phone:Pivot">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="phone:Pivot">
                <Grid>
                    <Grid.RowDefinitions>
                        <RowDefinition Height="Auto"/>
                        <RowDefinition Height="Auto"/>
                        <RowDefinition Height="*"/>
                    </Grid.RowDefinitions>
                    <Grid CacheMode="BitmapCache" Grid.RowSpan="2">
                        <Grid.Background>
                            <ImageBrush ImageSource="/Assets/bg_header.png"/>
                        </Grid.Background>
                    </Grid>
                    <Grid Background="{TemplateBinding Background}" CacheMode="BitmapCache" Grid.Row="2" />
                    <ContentPresenter ContentTemplate="{TemplateBinding TitleTemplate}" Margin="24,17,0,-7">
                        <StackPanel Orientation="Horizontal">
                            <Image Source="/Assets/company_name.png" Width="213.75" HorizontalAlignment="Left" VerticalAlignment="Top" />
                            <Button HorizontalAlignment="Right" VerticalAlignment="Top" Margin="140,-20,0,35" BorderThickness="0" x:Name="btnHome">
                                <Image Source="/Assets/btnHome.png" Width="48" Height="48" ></Image>
                            </Button>
                        </StackPanel>
                    </ContentPresenter>
                    <controlsPrimitives:PivotHeadersControl x:Name="HeadersListElement" Foreground="White"  Grid.Row="1"/>
                    <ItemsPresenter x:Name="PivotItemPresenter" Margin="{TemplateBinding Padding}" Grid.Row="2"/>
                </Grid>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

我想做的是:

var myButton = GetButtonWithName("btnHome") as Button;
myButton.Click += Handler;

然而,我无法得到按钮。任何解决方案?

1 个答案:

答案 0 :(得分:0)

我认为主要问题是如何在模板中找到控件。

所以我认为这个链接可以帮助你:

How to get Control from DataTemplate to ControlTemplate ?