2011-09-26 55 views
1

我想構建一個自定義Silverlight ItemsControl。我希望此控件的用戶使用XAML添加項目。這些項目將是其他UI元素。我想添加所有添加項目的邊距,因此我想添加一個ItemTemplate。不使用ItemsSource模板ItemControl項目

我正在試圖使用ItemsControl.ItemTemplate,但似乎沒有綁定到XAML中的元素時使用,即使用ItemsControl.Items屬性。 但是,如果我使用ItemsControl.ItemsSource屬性,則使用ItemTemplate。

有無論如何使用ItemTemplate,即使我沒有分配ItemsSource?

這是到目前爲止我的代碼

<ItemsControl x:Class="MyControl"> 
    <ItemsControl.ItemsPanel> 
     <ItemsPanelTemplate > 
      <toolkit:WrapPanel/>    
     </ItemsPanelTemplate> 
    </ItemsControl.ItemsPanel> 

    <ItemsControl.ItemTemplate> 
     <DataTemplate>   
      <StackPanel Margin="20" Background="Red"> 
       <TextBlock Text="Test text"/> 
       <ContentPresenter Content="{Binding}"/> 
      </StackPanel> 
     </DataTemplate> 
    </ItemsControl.ItemTemplate>   


    <ItemsControl.Template> 
     <ControlTemplate> 
      <Border> 
       <Grid> 
        <Grid.ColumnDefinitions> 
         <ColumnDefinition Width="*"/> 
         <ColumnDefinition Width="Auto" /> 
        </Grid.ColumnDefinitions> 

        <ItemsPresenter x:Name="ItemsPresenter"/> 

        <Button Command="{Binding SearchCommand}"/> 
       </Grid> 
      </Border> 
     </ControlTemplate> 
    </ItemsControl.Template> 
</ItemsControl> 

當我用我的控制

<MyControl> 
    <Button Content="Button"/> 
    <Button Content="Button"/> 
</MyControl> 

這引起了我的項目的顯示,用畫布面板佈局,但沒有應用的數據模板。 然後我發現this post提到了兩種重寫方法。

兒子在班上我的代碼隱藏我現在

protected override bool IsItemItsOwnContainerOverride(object item) 
{ 
    return false; 
} 

protected override void PrepareContainerForItemOverride(DependencyObject element, 
     object item) 
{ 
    base.PrepareContainerForItemOverride(element, item); 
    ((ContentPresenter)element).ContentTemplate = ItemTemplate; 
} 

但是 - 這讓我的兩個項目,與風格(即紅色文字塊),但沒有實際內容。列表中的按鈕不會被添加。這感覺就像我做錯了什麼 - 任何指針什麼?

謝謝!

回答

1

如果你想要做的就是添加一些保證金,然後你可以設置ItemContainerStyle,而不是指定一個模板:

<ItemsControl> 
    <ItemsControl.ItemContainerStyle> 
     <Style> 
      <Setter Property="FrameworkElement.Margin" Value="10" /> <!-- or whatever margin you want --> 
     </Style> 
    </ItemsControl.ItemContainerStyle> 
</ItemsControl> 

這將允許您設置容器控件的任何屬性(這在通過樣式,ItemsControl的情況將是ContentControl)。

+0

感謝您的快速響應!但是這在Silverlight中不可用,是嗎? –

+0

爲了澄清,我認爲ItemContainerStyle僅適用於ListBox和ComboBox,但不適用於ItemsControl。這只是在WPF中,至少根據[這篇文章](http://forums.silverlight.net/t/11291.aspx) –