2016-11-24 3 views
0

Я создаю пользовательский элемент управления пользователя. Моя цель - сделать управление повторно используемым. Я использую ItemsControl, вот XAMLМогу ли я привязать/установить свойство зависимостей типа Type к DataType DataTemplate

<ItemsControl ItemsSource="{Binding Path=ItemSource , RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type controls:MyItemsControlWithButtons}}}"> 
       <ItemsControl.ItemTemplate> 
        <DataTemplate DataType="{x:Type Type=typeOf(DataTemplateType)????}"> 
         <ContentControl x:Name="instruction" Content="{Binding Path=DataTemplateControl, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type controls:MyItemsControlWithButtons}}}"/> 
         <DataTemplate.Triggers> 
          <Trigger Property="ItemsControl.AlternationIndex" Value="0"> 
           <Setter Property="Background" Value="#DDDDDD" TargetName="instruction" /> 
          </Trigger> 
          <Trigger Property="ItemsControl.AlternationIndex" Value="1"> 
           <Setter Property="Background" Value="#EEEEEE" TargetName="instruction" /> 
          </Trigger> 
         </DataTemplate.Triggers> 
        </DataTemplate> 
       </ItemsControl.ItemTemplate> 
</ItemsControl> 

Вот управление: MyItemsControlWithButtons

public partial class DraggableItemsControlWithButtons : UserControl 
    { 
     public DraggableItemsControlWithButtons() 
     { 
      InitializeComponent(); 
     } 

     public static readonly DependencyProperty DataTemplateTypeProperty = 
     DependencyProperty.Register(nameof(DataTemplateType), typeof(Type), typeof(DraggableItemsControlWithButtons), new UIPropertyMetadata(null)); 
     public Type DataTemplateType 
     { 
      get { return (Type)GetValue(DataTemplateTypeProperty); } 
      set { SetValue(DataTemplateTypeProperty, value); } 
     } 

     public static readonly DependencyProperty ItemSourceProperty = 
     DependencyProperty.Register(nameof(ItemSource), typeof(IEnumerable), typeof(DraggableItemsControlWithButtons), new UIPropertyMetadata(null)); 
     public IEnumerable ItemSource 
     { 
      get { return (IEnumerable)GetValue(ItemSourceProperty); } 
      set { SetValue(ItemSourceProperty, value); } 
     } 

     public static readonly DependencyProperty DataTemplateControlProperty = 
     DependencyProperty.Register(nameof(DataTemplateControl), typeof(Control), typeof(DraggableItemsControlWithButtons), new UIPropertyMetadata(null)); 
     public Control DataTemplateControl 
     { 
      get { return (Control)GetValue(DataTemplateControlProperty); } 
      set { SetValue(DataTemplateControlProperty, value); } 
     } 
    } 

Как вы можете видеть, что я хочу, чтобы связать/набор DataTemplateType к ТипДанному из ItemsControl.ItemTemplate в DataTemplate

Как я могу это достичь?

Спасибо

+0

Это ISN 't необходимо установить DataType здесь, потому что вы явно присвоили DataTemplate свойству ItemTemplate. Нет выбора автоматики по типу данных. – Clemens

+0

Возможно, вам захочется установить ItemTemplate извне. Создайте свойство depedency типа DataTemplate в UserControl и привяжите к нему ItemTemplate ItemsSource. – Clemens

+0

@Clemens Можете ли вы предоставить пример кода? –

ответ

1

Вы можете probaby упростить управление заменой DataTemplateControl имущества путем ItemTemplate собственности. Чтобы завершить сходство с ItemsControl, переименуйте свойство ItemSource в ItemsSource.

public static readonly DependencyProperty ItemsSourceProperty = 
    DependencyProperty.Register(
     nameof(ItemsSource), typeof(IEnumerable), 
     typeof(DraggableItemsControlWithButtons)); 

public IEnumerable ItemsSource 
{ 
    get { return (IEnumerable)GetValue(ItemsSourceProperty); } 
    set { SetValue(ItemsSourceProperty, value); } 
} 

public static readonly DependencyProperty ItemTemplateProperty = 
    DependencyProperty.Register(
     nameof(ItemTemplate), typeof(DataTemplate), 
     typeof(DraggableItemsControlWithButtons)); 

public DataTemplate ItemTemplate 
{ 
    get { return (DataTemplate)GetValue(ItemSourceProperty); } 
    set { SetValue(ItemSourceProperty, value); } 
} 

ItemsControl в XAML в UserControl была бы выглядеть следующим образом:

<ItemsControl 
    ItemsSource="{Binding ItemsSource, 
          RelativeSource={RelativeSource AncestorType=UserControl}}" 
    ItemTemplate="{Binding ItemTemplate, 
          RelativeSource={RelativeSource AncestorType=UserControl}}" /> 

Вы бы затем присвоить ItemTemplate так же, как в любой другой элемент управления с ItemTemplate собственности:

<local:DraggableItemsControlWithButtons ItemSource="{Binding ...}"> 
    <local:DraggableItemsControlWithButtons.ItemTemplate> 
     <DataTemplate> 
      ... 
     </DataTemplate> 
    </local:DraggableItemsControlWithButtons.ItemTemplate> 
</local:DraggableItemsControlWithButtons> 
+0

Причина, по которой я хотел «скрыть»/encapsualte ItemTemplate - это триггеры и стиль. Я хочу, чтобы избежать определения того же в нескольких местах –

+0

Не уверен, что это значит. Теперь у вас есть свойство DataTemplateControl, которое должно быть установлено. «Обычный» подход - иметь свойство ItemTemplate. – Clemens

+0

Я добавил DataTemplate.Triggers на мой вопрос, чтобы показать, что я имел в виду –

 Смежные вопросы

  • Нет связанных вопросов^_^