Get clicked object from ItemsControl and populate Popup with its properties

有些话、适合烂在心里 提交于 2021-02-02 09:57:25

问题


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:


Cast the DataContext of the sender argument in the event handler to your data type:

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


来源:https://stackoverflow.com/questions/46217175/get-clicked-object-from-itemscontrol-and-populate-popup-with-its-properties

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!