2015-09-04 109 views
1

我想要構建一個UserControl,我可以綁定ItemsSource並顯示對象的縮略圖集合。爲了讓它儘可能通用,我想接受沒有任何類型的IEnumerable,並將Image Propertyname傳遞給usercontrol。WPF在Xaml中的ItemsSource中設置Propertyname

爲此,我添加了兩個DependencyPropertys(ItemsSource(IEnumerable),BitmapImagePath(string))。

<UserControl x:Class="UserControls.ThumbnailListControl" 
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
      xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
      xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
      d:DesignHeight="300" 
      d:DesignWidth="300" 
      mc:Ignorable="d"> 
    <UserControl.Resources> 
     <styles:SharedResourceDictionary> 
      <DataTemplate x:Key="DataItem"> 
       <Image Source="{Binding}" /> 
      </DataTemplate> 
     </styles:SharedResourceDictionary> 
    </UserControl.Resources> 
    <Grid> 
     <ItemsControl VerticalAlignment="Stretch" 
         ItemTemplate="{StaticResource DataItem}" 
         ItemsSource="{Binding RelativeSource={RelativeSource AncestorType={x:Type userControls:ThumbnailListControl}}, 
              Path=ItemsSource}"> 
      <ItemsControl.ItemsPanel> 
       <ItemsPanelTemplate> 
        <VirtualizingStackPanel Orientation="Vertical" /> 
       </ItemsPanelTemplate> 
      </ItemsControl.ItemsPanel> 
     </ItemsControl> 
    </Grid> 
</UserControl> 

我不知道如何通過綁定屬性名稱「BitmapImagePath」來歸檔。一個可能的解決方案是在代碼後面使用反射,但我認爲這不是優雅的解決方案。

在父用戶控件我wan't到包括ThumbnailList<ThumbnailListControl ItemsSource="MyItemsSource" BitmapImagePath="ThumbnailImage" />

回答

0

首先,給您的自定義用戶控件的名稱:x:Name="MyUserControl"。 然後在你的DataTemplate簡單地綁定到其依賴屬性:取自

... 
<DataTemplate x:Key="DataItem"> 
    <Image Source="{Binding ElementName=MyUserControl, Path=BitmapImagePath}" /> 
</DataTemplate> 
... 

答:Binding UserControl to its own dependencyProperty doesn't work

+0

的問題是不依賴屬性綁定。在我的ItemsSource中有多個具有屬性「ThumbnailImage」的對象。該屬性應該用於圖像源。 – take

+0

所以我認爲使用''應該可以正常工作。如果沒有,您可以嘗試將您的DataTemplate直接放入您的ItemsControl中,而不將其解壓縮到UserControl.Resources。 –