【问题标题】:ListBox display selected Items (Image) in another ListBox (Selection Mode Multiple)ListBox 在另一个 ListBox 中显示选定的项目(图像)(多选模式)
【发布时间】:2011-12-19 12:56:05
【问题描述】:

我只是想在SelectionChanged 事件中试验一些ListBox 功能。

我有以下控件:

1.ListBox : Name = ListBoxSource(我刚刚在 XAML 中添加了Image

2.ListBox : 名称 = ListBoxDisplay

我只想迭代并从ListBoxSource 中选择这些项目并将其显示到ListBoxDisplay。如何在循环中做到这一点?

ListBoxSource上的Item只有Image控件,没有其他控件。

我在网上找不到任何解决方案,因为大多数示例/解决方案都使用TextBlockTextBoxCheckBox ...而没有Images

foreach (Object selectedItem in ListBox1.SelectedItems)
{
    // What to do in here to add the selected Images to "ListBoxDisplay"
}

【问题讨论】:

  • 你不应该需要一个循环。您是否尝试简单地将 ListBoxDisplay.Items 绑定到 ListBoxSource.SelectedItems?
  • @Martin:是的,我确实试过那个。 DataContext="{Binding ElementName=ListBoxSource, Path=SelectedItems}" 但“ListBoxDisplay”上没有显示
  • @H.B:是的..我的意思是即使示例使用 TextBlock 或其他控件,我也很难理解,因为我认为它可以显示一个字符串,这是这些控件的默认值。我的是图片
  • 你做了一个错误的假设,这些项目绝对可以是任何东西,如果它是可以显示的东西,ListBox 就会显示它。
  • 使用:ItemsSource="{Binding ElementName=ListBoxSource, Path=SelectedItems}" 而不是 DataContext="..."

标签: c# .net wpf silverlight


【解决方案1】:

使用这个

 <ListBox x:Name="ListBoxDisplay"
          ItemsSource="{Binding ElementName=ListBoxSource, Path=SelectedItems}"/>

而不是所有的代码。

另外:使用 DataTemplate 和 DataBinding 填充 ListBox,这将使这种结构更加健壮和灵活。

【讨论】:

  • 这行得通......谢谢......所以你认为我的 ItemTemplate 是错误的?在我的“ListBoxSource”上选择和取消选择一个项目没有问题,只有选定的项目消失了(可能没有显示)。我的意思是从字面上看,这些选定项目的图像不再显示。
  • 他们还占用屏幕空间吗?
  • 是的..还有屏幕空间.. 项目的选择和剖析工作正常并准确显示所选项目但第一次选择项目时图像消失了选择突出显示仍然存在但有没有更多的图像。 (即使没有更多图像,您仍然可以取消选择,因为空间仍然存在)
  • 我对此提出了另一个问题并发布了我的代码。 stackoverflow.com/questions/8563164/…
【解决方案2】:
for(int i=0;i<ListBoxSource.Items.Count;i++)
{
   Image currentImageItem = ListBoxSource.Items[i] as Image;
        Image image = new Image();
        image.Source = currentImageItem.Source ; 
   ListBoxDisplay.Items.Add(image);
}

抱歉我的错误,这段代码应该可以工作 您必须处理其他属性,例如宽度和高度

【讨论】:

  • 我在使用上面的代码时遇到了一个错误:“元素已经有一个逻辑父级。它必须先从旧父级分离,然后才能附加到新父级”
  • @user1078782:这就是为什么你应该避免使用 UI 元素列表。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-07-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-07-17
相关资源
最近更新 更多