如何获取ListView项目ID

时间:2013-03-16 00:00:56

标签: c# windows-runtime winrt-xaml

我有这个带有TextBox和CheckBox的ListView:

<ListView x:Name="ActiveTasksListView" ItemsSource="{Binding Path=ActiveTasks}" SelectedItem="{Binding Id}">

<ListView.ItemsPanel>
    <ItemsPanelTemplate>
        <StackPanel Orientation="Vertical" Margin="37,0,17,0" />
    </ItemsPanelTemplate>
</ListView.ItemsPanel>

<ListView.ItemTemplate>
    <DataTemplate>
        <Border Background="White">
            <TextBlock Text="{Binding Name}" />
            <CheckBox Click="CheckBox_Click_1" />
        </Border>
    </DataTemplate>
</ListView.ItemTemplate>

</ListView>

如果我点击CheckBox,我需要在Message Dialog()中显示点击项目的Id(来自数据源)

2 个答案:

答案 0 :(得分:0)

使用VisualTreeHelper并单击CheckBox元素,您可以找到ListViewItem,然后获取其Id属性

void CheckBox_Click_1(object sender, RoutedEventArgs e)
{
    var item = sender as DependencyObject;

    while (!(item is ListViewItem))
    {
        item = VisualTreeHelper.GetParent(item);
    }

    var id = ((ObjectClass) item).Id;
}

答案 1 :(得分:0)

void CheckBox_Click_1(object sender, RoutedEventArgs e)
{
    var cb = sender as CheckBox;
    dynamic itemVM = cb.DataContext;
    var id = itemVM.Id;
}