开发者

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开发者_如何学C") 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>


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.


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜