2011-10-24 20 views
5

我有一個名爲JUC的用戶控件的WPF列表框。WPF不同類型的用戶控件列表

這很好,因爲我對WPF很陌生,這已經非常令人印象深刻。我現在想要做的是根據綁定屬性在列表中擁有不同的用戶控件。

這可能嗎?如果不是,我該怎麼做到呢?

我使用的是一個列表,因爲我想允許用戶控件的拖放順序排列,並且會有一個可變數字,這似乎是有意義的 - 可選方法是受歡迎的。

<ListBox x:Name="peopleListBox" 
    HorizontalAlignment="Stretch" 
    VerticalAlignment="Stretch" 
    ItemContainerStyle="{StaticResource ListBoxItemStretch}" 
    Foreground="Transparent" 
    BorderBrush="Transparent" 
    Background="Transparent" 
    Grid.ColumnSpan="2" SelectionChanged="peopleListBox_SelectionChanged"> 
     <ListBox.ItemTemplate> 
      <DataTemplate> 
       <Grid> 
        <my:JUC Margin="4"></my:JUC> 
       </Grid> 
      </DataTemplate> 
     </ListBox.ItemTemplate> 
    </ListBox> 

回答

7

您可以使用DataTemplateSelector,在SelectTemplate()方法可以檢查的DataTemplate對於目前該項目已通過使用其中:

在XAML:

<!-- define templates in resources 
    ChartDataTemplate is a ChartDataTemplate.xaml, the same for other 
--> 
<UserControl.Resources> 
    <DataTemplate x:Key="ChartDataTemplate"> 
      <views:LineChartView /> 
    </DataTemplate> 

    <DataTemplate x:Key="GridDataTemplate"> 
     <views:PieChartView /> 
    </DataTemplate> 
</UserControl.Resources> 

<!-- ListView Itemtemplate should point to template selector --> 
<ItemsControl.ItemTemplate>  
    <DataTemplate> 
     <ContentPresenter 
      ContentTemplateSelector = "{StaticResource MyTemplateSelector}"> 

在後面的代碼:

private sealed class MyTemplateSelector: DataTemplateSelector 
{ 

    public override DataTemplate SelectTemplate(
             object item, 
             DependencyObject container) 
    { 
     // 1. case item to your object which is bound to each ListView item 
     // 2. based on object type/state return correct DataTemplate 
     // as this.Resources["ChartDataTemplate"] or 
     // this.Resources["GridDataTemplate"] 
    } 
    } 
+0

非常感謝! – Jonno