2011-10-24 38 views
5

Tôi có một hộp danh sách WPF có một điều khiển người dùng được gọi là JUC.WPF Danh sách các loại điều khiển người dùng khác nhau

Công trình này tuyệt vời và vì tôi rất mới với WPF, điều này đã rất ấn tượng. Những gì tôi muốn làm bây giờ là có điều khiển người dùng khác nhau trong danh sách dựa trên một tài sản bị ràng buộc.

Điều này có khả thi không? Nếu không, làm thế nào khác tôi nên đạt được điều này?

Tôi đang sử dụng danh sách vì tôi muốn cho phép đặt hàng thả/kéo của các điều khiển người dùng và sẽ có một số biến để có vẻ hợp lý - phương pháp thay thế được hoan nghênh.

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

Trả lời

7

Bạn có thể sử dụng DataTemplateSelector, trong SelectTemplate() phương pháp mà bạn có thể kiểm tra DataTemplate để sử dụng cho hiện thông qua vào mục:

Trong 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}"> 

Trong Mã đằng sau:

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

Cảm ơn rất nhiều! – Jonno

Các vấn đề liên quan