Russ
Russ

Reputation: 11

Windows Phone 7 Linking to events inside DataTemplates

I have a listbox where I create a Itemtemplate with a DataTemplate. I want to be able to write events for the checkboxes and buttons in the datatemplate but they do not seem to be firing.

Here is my xaml and basically I just tried to display a messagebox.show("worked") in the event function.

<ListBox x:Name="ListBox_Items" Margin="0,91,0,8" Foreground="#FF4BE5DB">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <StackPanel Orientation="Horizontal" Width="700">
                <CheckBox IsChecked="{Binding needPurchase}" Click="NeedPurchase_Click"  Name="CheckBox_NeedPurchase"/>
                <CheckBox IsChecked="False" Name="InCart"/>
                <StackPanel Orientation="Vertical">
                    <TextBlock Text="{Binding name}"/>
                    <TextBlock Text="{Binding storeLocation}"/>
                </StackPanel>
                <Button HorizontalAlignment="Right" Content="DELETE" Click="Button_Click" />
            </StackPanel>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

Upvotes: 1

Views: 1136

Answers (3)

Boryana Miloshevska
Boryana Miloshevska

Reputation: 2730

I agree that using commands is the best approach.

However if you still want to assess controls placed inside the ItemTemplate/DataTemplate (and subscribe to some events), then you can do this by using the VisualTreeHelper.

Upvotes: 1

Derek Lakin
Derek Lakin

Reputation: 16319

Because the items are defined within a DataTemplate they are not hooked up to the code-behind for the parent class. If you want to handle events for templated items, then you should consider using commands instead. If you don't know what commands are (and therefore unlikely to know what MVVM is), then you should check out an explanation like this by Jeremy Likness.

Upvotes: 2

Steve Chadbourne
Steve Chadbourne

Reputation: 6953

For starters you need to remove the name from all the controls in the template. If you have 10 items in the list you will have 10 sets of controls with the same name which won't work.

Upvotes: -2

Related Questions