1

Hey everyone. I'm new to Silverlight and would like to access a button control that is part of a ListBoxItem. However, I'm not quite sure how to do this. My XAML is:

<DataTemplate x:Key="ItemTemplate2">
            <Grid Height="51">
                <TextBlock x:Name="tbName" Text="{Binding Property1}" Margin="0,0,98,0" d:LayoutOverrides="Height" Grid.ColumnSpan="2" HorizontalAlignment="Left" VerticalAlignment="Center"/>
                <Button x:Name="btnInfo"  HorizontalAlignment="Right" Margin="0,-11,0,0" Width="87" Height="54" VerticalAlignment="Top" Background="#FF8EC1D2" BorderBrush="#FF8EC1D2" BorderThickness="0">
                    <Image Source="../Images/btnNameImage.png" Stretch="None"/>                 
                </Button>
            </Grid>
        </DataTemplate>

How can I access the "btnInfo" from the code-behind?

Thanks for any help

3
  • What property of btnInfo are you trying to access? You should be able to use it by "btnInfo" directly... Commented Jun 25, 2010 at 17:42
  • It's part of a DataTemplate so it will be in a different namescope than the page's XAML and won't be accessible directly in the code-behind. What exactly are you trying to do with the button? Commented Jun 25, 2010 at 17:46
  • I'd like to change the Image of the button. Commented Jun 25, 2010 at 17:49

2 Answers 2

1

you wont be able to access it directly from code behind, but you should be able to do what you want by registering an event with it. Add a Loaded event to the button then in your codebehind define the corresponding method.

protected btninfo_Loaded(object sender, EventArgs e)
{
    Button btnInfo = (Button) sender;
    //do whatever you need to do
}

obviously you can do the same thing to handle click events or whatever you want.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks. I'd like to perform this for every button in the list, not just the selected one. I also tried creating a storyboard for the image replacement, but I can't access the storyboard from the code behind.
this should run whenever one of your DataTemplates is loaded into a Template, is this not happening? can you please show more of your code (like the ItemsControl that is hosting the templates?
Thanks. I needed to get access of the buttons from outside any of the button events themselves. So I stored each button in an array (in the laoded event) and make the array a class level variable. This works fine. Thanks again!
0

This doesn't directly answer your question of programatically accessing a data template, but how about Binding?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.