簡體   English   中英

將圖像控件綁定到列表框所選項目

[英]binding image control to listbox selected item

我有一個列表框,位於項目模板的內部,以及位於數據模板的內部(與往常一樣)。 我的目標是-在列表框選擇更改事件中,我想將列表框選擇的項目綁定到圖像控件-我的代碼是-

ListBox lb = (ListBox)sender;

ListBoxItem item = (ListBoxItem)lb.SelectedItem;

Image im = (Image)item.Content;
Image1.Source = new BitmapImage(((BitmapImage)im.Source).UriSource);

我的ListBox.ItemTemplate看起來像這樣:

<ListBox Name="imageList" Height="556" Width="130" HorizontalAlignment="Left" Style="{StaticResource ListBoxStyle1}" SelectionChanged="imageList_SelectionChanged" >
   <ListBox.ItemTemplate>
      <DataTemplate>
         <Image Source="{Binding Imgs}" Width="100" Height="100"/>
      </DataTemplate>
   </ListBox.ItemTemplate>
</ListBox>

但它顯示出異常。 Image1是我的圖像控件,我不想在xaml中綁定圖像源。 我有一些要求。

您之所以興奮,是因為當您綁定ListBox ,並且我假設您這樣做,或者與此相關的任何ItemsControl時, ItemsSelectedItemSelectedItems之類的屬性都將是綁定列表項的類型,而不是ListBoxItem ,它只是容器。 如果您需要ListBoxItem像這樣引用它:

var listBox = sender as ListBox;
var lbi = (ListBoxItem)listBox
                         .ItemContainerGenerator
                         .ContainerFromItem(listBox.SelectedItem)

但是如果您的ImageDataTemplate一部分,它將不會如獲得Content那樣容易。 同樣,它將是一種綁定項,基本上指向與SelectedItem相同的項。 也許您可以使用它,否則您將需要引用VisualTreeHelper ,因為默認情況下, ListBoxItem和您的DataTemplate Image之間的可視樹中將存在其他控件。 我不理解您不想綁定Image.Source但是為什么不綁定回ListBox.SelectedItem ,然后可以引用您的對象。

如果要使用SelectedItem圖像更新Image1.Source ,則SelectionChange方法應如下所示:

Image1.Source = ((sender as ListBox).SelecteItem as img).Imgs;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM