2011-11-28 42 views
2

我有以下的產品列表模板snipet設置一個用戶控件作爲一個DataTemplate

<Style x:Key="ProductListStyle" TargetType="{x:Type s:SurfaceListBox }"> 
     <Setter Property="Background" Value="{DynamicResource {x:Static s:SurfaceColors.ListBoxItemBackgroundBrushKey}}" /> 
     <Setter Property="SelectionMode" Value="Single" /> 
     <Setter Property="Height" Value="234" /> 
     <Setter Property="ItemTemplateSelector"> 
      <Setter.Value> 
       <sc:ProductListTemplateSelector> 
        <sc:ProductListTemplateSelector.NormalItemTemplate> 
         <DataTemplate> 
          <StackPanel RenderTransformOrigin="0.5, 0.5"         
          Margin="7,0,0,0" 
          MinWidth="171" MaxWidth="171"         
          MinHeight="235" MaxHeight="235"> 
           <Image Margin="14,21,21,11" Source="{Binding [email protected]}" 
         Height="149" Width="101" /> 
           <TextBlock Text="{Binding [email protected]}" 
         MaxWidth="116" 
         FontSize="12"     
         Margin="21,0,21,21" 
         FontFamily="Segoe360" 
         TextAlignment="Center" 
         TextWrapping="Wrap" 
         Foreground="{DynamicResource {x:Static s:SurfaceColors.ListBoxItemForegroundBrushKey}}" 
         HorizontalAlignment="Center" /> 
          </StackPanel> 

         </DataTemplate> 
        </sc:ProductListTemplateSelector.NormalItemTemplate> 

我需要更換這種風格的DataTemplate中使用像

<local:MyUserControl> 

我的用戶控制設置通過只保留部分之間我沒有得到我的控制顯示時,我的Itemsource設置與myUserControl的集合

+0

你試過我的建議嗎? – sll

+0

你的'ItemsSource'是'MyUserControl'或某個對象的集合嗎? – Rachel

回答

1

通常我只是將DataTemplate添加到Resources。如果數據模板是全局數據模板,則這可以是<Window.Resources><App.Resources>,如果模板只應用於指定範圍,則可以使用FrameworkElement.Resources。例如,將模板添加到ListView.Resources只會應用特定ListView中的模板。

<Window.Resources> 
    <DataTemplate DataType="{x:Type local:ProductModel}"> 
     <local:MyUserControl /> 
    </DataTemplate> 
</Window.Resources> 

作爲一個側面說明,你原來的問題使我相信,你是一個ListView結合MyUserControl對象的集合。我真的不會推薦這個,但是如果是這種情況,你可以在你的DataTemplate中使用ContentControl,它的Content綁定到你的對象,它應該正確顯示。

<ContentControl Content="{Binding }" /> 
+0

你好rachel,你說你不會推薦它的原因是什麼? – serge

+1

@ user930203您正在內存中存儲列表中每個項目的UI對象。將您的數據保留在內存中並允許WPF根據需要繪製UI元素更有效。例如,將'Product'數據類的列表存儲在內存中,並告訴WPF使用'MyUserControl'作爲模板來繪製'Product'對象,而不是將'ProductUserControl'存儲在內存中爲每個「產品」對象。這也使您能夠利用WPF的虛擬化,在渲染新項目時將重新使用現有模板,而不是構建新項目。 – Rachel

+0

@ user930203如果您還沒有,我會強烈建議在使用WPF時查看MVVM設計模式。它非常適合WPF的綁定系統,並且可以輕鬆創建和維護代碼。下面是我寫的一個簡短的介紹,如果你感興趣的話:http://rachel53461.wordpress.com/2011/05/08/simplemvvmexample/ – Rachel

相關問題