如何在ListBox ItemTemplate中按钮单击期间识别哪个itemSelected

时间:2011-08-01 01:04:09

标签: data-binding windows-phone

我有一个包含一个简单按钮的ItemTemplate。当我单击此按钮时,我需要一种方法来识别单击的行以拉出绑定到列表框的项目。

XAML

        <ListBox Name="DemoBox" SelectionChanged="listBox_SelectionChanged">
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <Grid Height="150">
                        <Grid.ColumnDefinitions>
                            <ColumnDefinition Width="400"/>
                            <ColumnDefinition/>
                        </Grid.ColumnDefinitions>
                        <Grid Height="120" Grid.Column="0">
                            <Grid.RowDefinitions>
                                <RowDefinition Height="60"/>
                            </Grid.RowDefinitions>
                            <TextBlock
                                    Grid.Row="0"
                                    Text="{Binding SomeObjProperty}"/>
                        </Grid>
                        <Grid Height="120" Grid.Column="1" Margin="0,-12,0,0">
                            <Button Click="ShowStuffOnMap_Click">
                                <Button.Background>
                                    <ImageBrush ImageSource="images/arrow.png"/>
                                </Button.Background>
                            </Button>
                        </Grid>
                    </Grid>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>

点击处理程序

    private void ShowStuffOnMap_Click(object sender, RoutedEventArgs e)
    {
        //sender is the button so ...
    }

提前谢谢

2 个答案:

答案 0 :(得分:5)

为什么在ListBox中有一个带有SelectionChanged事件的Click事件的Button?如果他们有不同的行动,这可以弥补一些可怕的用户体验!

通常的方法是使用数据绑定ListBox,然后使用SelectionChanged事件读出所选项目。

private void ListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    var listBox = sender as ListBox;
    var selectedItem = listBox.SelectedItem as MyDataBoundType;

    if (selectedItem != null)
    {
        // do stuff
    }

    // if you use the ListBox for navigation, set the SelectedIndex to -1
    // listBox.SelectedIndex = -1;
}

但如果你真的想要这样做,你需要使用Tag属性。

<Button Click="ShowStuffOnMap_Click" Tag="{Binding}">

然后在你的事件处理程序中:

private void ShowStuffOnMap_Click(object sender, RoutedEventArgs e)
{
    var button = sender as Button;
    var selectedItem = button.Tag as MyDataBoundType;
}

但我仍然认为你的方法是错误的,并且代表糟糕的用户体验,因为列表的常规方法是列表中的整个行只是一个选择。< / p>

答案 1 :(得分:0)

执行此操作的最佳方法是在模板中使用一些唯一标识符。例如,您有一个TextBlock - 给它一个唯一的名称,当按下该按钮时,在辅助网格中搜索带有标识符的TextBlock并读取其Text属性。 / p>

相关问题