gpt4 book ai didi

c# - 如何从其子控件访问 ListViewItem?

转载 作者:行者123 更新时间:2023-11-30 16:52:27 27 4
gpt4 key购买 nike

我有一些来自集合的 ListViewItem,我创建了一个 DataTemplate,这样每个 ListViewItem 都有一个 Button 作为子控件:

<Window.Resources>
<DataTemplate x:Key="ItemTemplate_AwesomeTemplate">
<StackPanel Orientation="Vertical" VerticalAlignment="Stretch">
<Button Content="Awesome Button" Click="Awesome_Button_Click" HorizontalContentAlignment="Center" VerticalAlignment="Bottom" FontWeight="Bold" Foreground="Black"/>
</StackPanel>
</DataTemplate>
</Window.Resources>

<ListView x:Name="AwesomeListView" HorizontalAlignment="Left" Height="577" VerticalAlignment="Top" Width="934" ScrollViewer.HorizontalScrollBarVisibility="Visible" Foreground="Black" Margin="10,10,0,0">
<ListView.View>
<GridView>
<GridViewColumn Header="AwesomeHeader" Width="250" CellTemplate="{StaticResource ItemTemplate_AwesomeTemplate}"/>
</GridView>
</ListView.View>
</ListView>

当我单击某个 Button 时,是否可以更改包含单击的 ListViewItemIsSelected 属性按钮?

最佳答案

要更改包含单击的 ButtonListViewItemIsSelected 属性,您应该使用 DataContext 来查找这样的项目:

private void Awesome_Button_Click(object sender, RoutedEventArgs e)
{
var item = (sender as Button).DataContext;
int index = AwesomeListView.Items.IndexOf(item);//find the index of the item that contains the clicked button
AwesomeListView.SelectedItem = AwesomeListView.Items[index];//set the AwesomeListView's SelectedItem to item that contains the clicked button
}

关于c# - 如何从其子控件访问 ListViewItem?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32549547/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com