单击列表视图上的按钮时,从列表视图中获取选定的项目ID

时间:2018-07-28 07:33:42

标签: wpf listview

下面是xamlListView

 <ListView x:Name="lvImages" ItemsSource="{Binding Path=resimGuncelle}" SelectedItem="{Binding Path=ID}">
            <ListView.View>
                <GridView>
                    <GridViewColumn>
                        <GridViewColumn.CellTemplate>
                            <DataTemplate>
                                <Image Name="MyImage" Source="{Binding RESIM_YOLU}" Width="120" Height="110" />
                            </DataTemplate>
                        </GridViewColumn.CellTemplate>
                    </GridViewColumn>
                    <GridViewColumn Header="Title" DisplayMemberBinding="{Binding FileName}" x:Name="txtx" x:Uid="dd" />
                    <GridViewColumn>
                        <GridViewColumn.CellTemplate>
                            <DataTemplate>
                                <Button Style="{StaticResource DaireButtonResimSil}" x:Name="btndil" Click="btndil_Click"/>
                            </DataTemplate>
                        </GridViewColumn.CellTemplate>
                    </GridViewColumn>
                </GridView>
            </ListView.View>
        </ListView>

我想获取“选定商品ID”,如下所示:

 private void btndil_Click(object sender, RoutedEventArgs e)
    {
        var selectedImageId = ((ResimGuncelleme)lvImages.SelectedItem).ID;

    }

1 个答案:

答案 0 :(得分:0)

如果我做对了,您的ItemDataModel项目就有一个ListView,并且它有一个Id属性。每次单击行预定义按钮时,您都希望获得该行项目的Id属性(无需选择该行,否则可以简单地检查ListView's SelectedItem属性)。

假设您的ItemModel看起来像这样:

public class ItemModel
{
    public string Id { get; set; }
    public BitmapSource ResimYolu { get; set; }
    public string FileName { get; set; }
}

在您的xaml中,您可以使用Button绑定在Tag的{​​{1}}中传递单击按钮的项目:

RelativeSource

您可以从按钮的点击处理程序中获取该项目的ID:

 <Grid>
    <ListView x:Name="lvImages" ItemsSource="{Binding Path=ResimGuncelle}" SelectedItem="{Binding Path=Id}">
        <ListView.View>
            <GridView>
                <GridViewColumn Header="Image">
                    <GridViewColumn.CellTemplate>
                        <DataTemplate>
                            <Image Name="MyImage" Source="{Binding ResimYolu}" Width="120" Height="110" />
                        </DataTemplate>
                    </GridViewColumn.CellTemplate>
                </GridViewColumn>
                <GridViewColumn Header="Title" DisplayMemberBinding="{Binding FileName}" x:Name="txtx" x:Uid="dd" />
                <GridViewColumn Header="Button">
                    <GridViewColumn.CellTemplate>
                        <DataTemplate>
                            <Button x:Name="btndil" Tag="{Binding RelativeSource={RelativeSource AncestorType={x:Type ListViewItem}}}"  Content="Button" Click="btndil_Click" />
                        </DataTemplate>
                    </GridViewColumn.CellTemplate>
                </GridViewColumn>
            </GridView>
        </ListView.View>
    </ListView>
</Grid>

Ps:这不是一个很干净的方法!