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

时间:2015-06-15 04:25:17

标签: c# .net xaml windows-phone-8 listbox

我有以下XAML代码..

<phone:PhoneApplicationPage.Resources>
    <DataTemplate x:Key="DataTemplate1" >
        <Border BorderBrush="LightGray" BorderThickness="1" Height="150" Width="500" >
            <Grid Width="500" Height="150" Background="White" >
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="0.5*"/>
                    <ColumnDefinition Width="2.5*"/>
                    <ColumnDefinition Width="1*"/>

                </Grid.ColumnDefinitions>
                <Grid.RowDefinitions>
                    <RowDefinition Height="*"/>
                </Grid.RowDefinitions>
                <Image Grid.Column="0" Height="Auto" Width="Auto" Source="/Images/notav.jpg" Margin="0,5,4,4" HorizontalAlignment="Left" />
                <TextBlock Text="{Binding PRICE}" TextWrapping="Wrap"  Grid.Column="1"  Width="350"  Foreground="Black" Height="60" Margin="30,85,20,-10"/>

                <TextBlock  Text="{Binding ITMNAME }" FontSize="22" TextWrapping="Wrap" Grid.Column="1"   Name="txtITMNAME" Foreground="DarkBlue" Width="500"  Height="130"  Margin="30,40,20,-10"/>

                <c4f:RoundButton   Grid.Column="2" Name="btntick" Click="btntick_Click" Grid.Row="0" FontSize="25" HorizontalAlignment="Right" Background="LightGray" Foreground="DarkGray" Margin="10,20,45,10"   />

            </Grid>
        </Border>
    </DataTemplate>

<ListBox Height="Auto" Name="lstbxmanual" ItemTemplate="{StaticResource DataTemplate1 }" Width="475" Margin="4,148,0,5" Background="White"  HorizontalAlignment="Left" Grid.RowSpan="2">
</ListBox>

我必须在代码后面访问圆形按钮,以更改其背景属性...

private void btntick_Click(object sender, RoutedEventArgs e)
{
    btntick. //not  able  to  access...
}

我已经完成了以下stackoverflow问题..

Access DataTemplate controls in code behind

MSDN link

它似乎与我的要求无关.. 请帮助我这方面......

2 个答案:

答案 0 :(得分:0)

解决方案1:使用x:Name代替Name

解决方案2:这也是另一种方式。

您可以投射事件发件人对象:

private void btntick_Click(object sender, RoutedEventArgs e)
{
    RoundButton rdbtn = sender as RoundButton;
    //rdbtn.BackColor
}

答案 1 :(得分:0)

请尝试,x:Name代替名称,可以从您的代码隐藏文件中访问。

<c4f:RoundButton   Grid.Column="2" x:Name="btntick" Click="btntick_Click" Grid.Row="0" FontSize="25" HorizontalAlignment="Right" Background="LightGray" Foreground="DarkGray" Margin="10,20,45,10"   />



private void btntick_Click(object sender, RoutedEventArgs e)
    {
       btntick.Foreground = Brushes.Blue;                    
    }

祝你好运。