2015-09-13 62 views
3

我有一個收集一些ListViewItem S,我創建了一個DataTemplate讓每位ListViewItemButton作爲子控件:如何從其子控件訪問ListViewItem?

<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,有沒有辦法來改變IsSelectedListViewItem的財產包含點擊Button

+1

如何變化?選擇,取消選擇或切換?如果切換,然後讓你考慮使用'ToggleButton'來代替? – dkozl

+0

@dkozl我只想選擇它先生。很抱歉,遲到的迴應。 – Wahyu

回答

2

要改變IsSelected財產ListViewItem的包含點擊Button你應該使用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 
} 
+0

謝謝你,先生,它完美的作品! :) – Wahyu