2013-07-26 45 views
0

我有以下XAML:自定義模板注射WPF

<ListView Name="_listView"> 
    <ListView.ItemTemplate> 
     <DataTemplate> 
      <Grid Name="_itemTemplate"> 
      </Grid> 
     </DataTemplate> 
    </ListView.ItemTemplate> 
</ListView> 

我想獲得是建立在我的後臺代碼的屬性,這將需要一個自定義用戶控件,並把它作爲一個動態模板。事情是這樣的:

public UserControl ItemTemplate 
{ 
    set { _itemTemplate.Content = value; } 
} 

於是我可以把我的控制窗口的XAML和申報項目模板是這樣的:

<local:MyCustomControl ItemTemplate="local:ControlThatActsAsItemTemplate"/> 

如何實現somtehing這樣呢?

+0

您需要創建附加的依賴項屬性。 –

回答

0

解決方案,它使用依賴屬性。

在定製UserControl聲明依賴屬性,將注入項目模板_listBox

public static readonly DependencyProperty ItemTemplateProperty = 
    DependencyProperty.Register("ItemTemplate", 
           typeof(DataTemplate), 
           typeof(AutoCompleteSearchBox), 
           new PropertyMetadata(ItemTemplate_Changed)); 

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

private static void ItemTemplate_Changed(
    DependencyObject d, 
    DependencyPropertyChangedEventArgs e) 
{ 
    var uc = (MyUserControl)d; 
    uc._listBox.ItemTemplate = (DataTemplate)e.NewValue; 
} 

現在你可以自由設定一個值,財產託管窗口XAML:

<Window.Resources> 
    <Style TargetType="local:MyUserControl"> 
     <Setter Property="ItemTemplate"> 
      <Setter.Value> 
       <DataTemplate> 
        <StackPanel> 
         <TextBlock Text="{Binding Path=PropertyName}"/> 
        </StackPanel> 
       </DataTemplate> 
      </Setter.Value> 
     </Setter> 
    </Style> 
</Window.Resources> 

_listBox在您的UserControl將獲得自定義ItemTemplate,它將響應您要設置爲數據源的自定義界面或類。

0

到目前爲止,我找到了以下簡單的解決方案。

在自定義控制XAML定義列表框:在XAML

public DataTemplate ItemTemplate 
{ 
    get { return _listBox.ItemTemplate; } 
    set { _listBox.ItemTemplate = value; } 
} 

在父窗口或控制資源集:

<ListBox Name="_listBox"/> 

在後面的代碼創建屬性

<Window.Resources> 
    <DataTemplate x:Key="CustomTemplate"> 
     <TextBlock Text="{Binding Path=SomeProperty}"/> 
    </DataTemplate> 
</Window.Resources> 

然後聲明自定義控件:

<local:CustomControl ItemTemplate="{StaticResource CustomTemplate}"/> 

現在您需要有一個接口公開SomeProperty和包含您需要設置爲_listBox.ItemsSource的接口實例的數據源。但這是另一回事。