【问题标题】:Get clicked object from ItemsControl and populate Popup with its properties从 ItemsControl 获取单击的对象并使用其属性填充 Popup
【发布时间】:2017-09-14 21:02:17
【问题描述】:

我有一个ItemsControl,它从我的视图模型的列表中显示对象。当用户单击 ItemsControl 中的项目时,我还有代码显示Popup。但是我不知道如何从单击的项目中获取实际对象以读取其属性并将它们显示在Popup 中。

我有一个ButtonClick 事件处理程序(用于在ItemsControl 中显示我的项目),我试图在调试器中查看按钮是否包含所需的对象,但显然它没有。

我还能如何获取对象并使用其属性填充弹出窗口?

<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>

【问题讨论】:

  • 您的弹出窗口是否在 XAML 中定义?
  • 点击的按钮应该在DataContext属性中有实际的数据对象。我建议使用 ListBox 而不是 ItemsControl(因为 ListBox 支持选择)并将 Poput 绑定到 SelectedItem 属性
  • 是的,弹出窗口在 XAML 中。但是是否可以像设置 ItemsControl 一样设置 ListBox(所有项目都包含在 StackPanel 中)?仅将 ItemsControl 替换为 ListBox 就足够了吗,还是我需要进行更多更改?

标签: wpf xaml


【解决方案1】:

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

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

【讨论】:

  • 好的,好像可以了!然后我需要将 dataObject 分配给 Popup 的 DataContext (myPopup.DataContext=dataObject) 并可以在 popup 的 XAML 中引用 dataObject 的属性:&lt;Popup&gt;&lt;TextBlock Text="{Binding Path=SomeProperty}"/&gt;&lt;/Popup&gt;
猜你喜欢
  • 2011-06-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-06-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多