ListView项目内的按钮-如何获取内容?

时间:2018-10-15 16:10:02

标签: listview binding uwp

我在DataTemplate控件中有一个Button。如何获取从列表视图项到按钮单击事件的传递值?

<ListView x:Name="listView1">
    <ListView.ItemTemplate>
        <DataTemplate x:DataType="x:String">
            <Grid>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="47"/>
                    <ColumnDefinition/>
                    <ColumnDefinition/>
                </Grid.ColumnDefinitions>
                <Image Source="Assets/placeholder.png" Width="32" Height="32" 
                       HorizontalAlignment="Left"/>
                <TextBlock Text="{x:Bind}" Foreground="Teal" 
                           FontSize="15" Grid.Column="1"/>
                <Button Content="Click Me" x:Name="Bttn" Click="Bttn.Click"/>
            </Grid> 
        </DataTemplate>
    </ListView.ItemTemplate>
    <x:String>Item 1</x:String>
    <x:String>Item 2</x:String>
    <x:String>Item 3</x:String>
    <x:String>Item 4</x:String>
    <x:String>Item 5</x:String>
</ListView>

private void Bttn_Click(object sender, RoutedEventArgs e)
{
    //Write text from item
}

1 个答案:

答案 0 :(得分:0)

只需将项目添加到按钮的 DatContext 并在单击的事件中进行检索。

<ListView x:Name="listView1">
    <ListView.ItemTemplate>
        <DataTemplate x:DataType="x:String">
            <Grid>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="47"/>
                    <ColumnDefinition/>
                    <ColumnDefinition/>
                </Grid.ColumnDefinitions>
                <Image Source="Assets/placeholder.png" Width="32" Height="32" 
                       HorizontalAlignment="Left"/>
                <TextBlock Text="{x:Bind}" Foreground="Teal" 
                           FontSize="15" Grid.Column="1"/>
                <Button Content="Click Me" x:Name="Bttn" Click="Bttn.Click" 
DataContext="{x:Bind}" />
            </Grid> 
        </DataTemplate>
    </ListView.ItemTemplate>
    <x:String>Item 1</x:String>
    <x:String>Item 2</x:String>
    <x:String>Item 3</x:String>
    <x:String>Item 4</x:String>
    <x:String>Item 5</x:String>
</ListView>

private void Bttn_Click(object sender, RoutedEventArgs e)
{
    //Write text from item
    string item = ((sender as Button).DataContext) as string;
}