Get clicked object from ItemsControl and populate Popup with its properties

时间:2017-09-14 10:53:07

标签: wpf xaml

I've got an ItemsControl which displays objects from a list from my viewmodel. I also have code to display a Popup when the user click on an item in the ItemsControl. However I don't know how to get the actual object from the clicked item to read its properties and display them in the Popup.

I've got a Click event handler for the Button (which is used to display my items in the ItemsControl) and I tried to see in the debugger if the button contains the desired object but apparently it doesn't.

How else can I get the object and populate the popup with its properties?

<ItemsControl ItemsSource="{Binding RecipientsNames}">
    <ItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
            <StackPanel Orientation="Horizontal"/>
        </ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <Button x:Name="btnConvoContact" Click="BtnConvoContact_Click"
                    Background="White" Foreground="Black" Cursor="Hand"
                    Width="Auto" Height="14" Padding="0" BorderThickness="0" Margin="0 0 6 0" HorizontalAlignment="Left" VerticalAlignment="Top">
                <TextBlock Text="{Binding Path=Name}" FontSize="12" Margin="0 -2 0 -2"/>
            </Button>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

1 个答案:

答案 0 :(得分:2)

将事件处理程序中DataContext参数的sender强制转换为您的数据类型:

private void BtnConvoContact_Click(object sender, RoutedEventArgs e)
{
    Button btn = sender as Button;
    var dataObject = btn.DataContext as YourDataClass;
}